/**
 * Created by wry on 2014/12/11.
 */
/*  宝宝树66小区二次改造    add   gct  20170804   start   */
var AmbassadorCommunity=mongoose.model('ambassador_community');
/*  宝宝树66小区二次改造    add   gct  20170804   end   */
var Question = mongoose.model('question');
var QuestionReplyStatistics = mongoose.model('question_replystatistics');
var Dic = mongoose.model('masterData_Dictionaries');
var Community = mongoose.model('community');
var toolUtil = require('../common/utils/toolUtil');
var messageUtil = require('../common/utils/messageUtil');
var Users = mongoose.model('user');
var async = require('async');
var UserFollowups = mongoose.model('user_followups');
var SystemMessage = mongoose.model('system_messages');
var questionService = require('../services/questionService');
var moment = require('moment');
var QuestionReplyPraise = mongoose.model('question_replypraises');
var QuestionReport = mongoose.model('question_reports');
var QuestionAndReplyCount = mongoose.model('question_replycounts');
var QuestionReplyThank = mongoose.model('question_replythanks');
var freshNews = mongoose.model('system_freshNews');
var pushRecords = mongoose.model('system_pushRecords');
var ugcIndex = mongoose.model('system_ugcIndex');
var neighbourActivity = mongoose.model('activity_neighbour');
var ugcReply = mongoose.model('system_ugcReply');
var AdoptedCount = mongoose.model('question_adoptedcounts');
var replyAt = mongoose.model('question_replyAt');
var recentContact = mongoose.model('user_recentContactPerson');
var replyAtService = mongoose.model('question_replyAtService');
var mysqlUtil = require('../common/utils/mysqlUtil');
var QuestionReport = mongoose.model('question_reports');

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  start   */
// 置顶，精华，屏蔽
var userService = require('../services/userService');
var ModeratorManagerOperationNote = mongoose.model('moderatorManagerOperationNote'); // 小区大使置顶精华屏蔽操作记录
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  end   */
/**
 * ==================================提问==================================
 */

/**
 * 提问新接口
 * @param token
 * @param input
 * @param callback
 */
exports.postQuestionNewService = function (token, input, callback) {

    var pushFlag = input.category;
    if (input.category == 'activity') {
        input.category = 'share'
    }
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var question;
            var tags;
            var tag;
            var desc = input.desc.replace(/[\n\r]{2,}/g, "\n").trim();

            var temp = new Question();
            temp.category = input.category;
            temp.desc = desc;
            temp.images = input.images;
            temp.status = '未解决';
            temp.createdBy = user._id;
            temp.community = user.community._id;

            //打标签
            restClient.get('http://' + RecommendHost + ':8002?data=' + input.desc, function (data, response) {
                if (response.statusCode == 200 && data != null && data != 'unknown' && data != '') {
                    try {
                        var sensitive = JSON.parse(data).sensitive;
                        tags = JSON.parse(data).tag;

                        if (sensitive != null) {
                            temp.desc = sensitive;
                        }

                        Dic.find({'value': {'$in': tags}, 'category': '02'}, '_id', function (err, res) {
                            if (res != null) {
                                temp.tag = res;
                                tag = res;
                            }
                            temp.save(function (err, result) {

                                var data = {
                                    question: result,
                                    tag: tag,
                                    tags: tags,
                                    user: user,
                                    input: input,
                                    pushFlag: pushFlag
                                };

                                callback(null, data);
                            });
                        });
                    } catch (e) {
                        logger.error("postNewQuestion--tag--" + e);
                        temp.save(function (err, result) {
                            var data = {
                                question: result,
                                tag: tag,
                                tags: tags,
                                user: user,
                                input: input,
                                pushFlag: pushFlag
                            };
                            callback(null, data);
                        })
                    }
                } else {
                    temp.save(function (err, result) {
                        var data = {
                            question: result,
                            tag: tag,
                            tags: tags,
                            user: user,
                            input: input,
                            pushFlag: pushFlag
                        };
                        callback(null, data);
                    })
                }
            }).on('error', function (err) {
                logger.error('get question tag around went wrong on the request' + err.message);

                temp.save(function (err, result) {
                    var data = {
                        question: result,
                        tag: tag,
                        tags: tags,
                        user: user,
                        input: input,
                        pushFlag: pushFlag
                    };
                    callback(null, data);
                })
            });
        }
    });
};

exports.pushQuestionService = function (user, tag, tags, question, input, pushFlag) {
    async.series([
        //推送给已关注问题发起者的用户
        function (callbackInner) {
            UserFollowups.find({'followUser': question.createdBy}, 'user').populate('user', '_id community').exec(function (err, results) {
                if (results != null && results.length > 0) {

                    var users = [];
                    results.forEach(function (result) {

                        if (result.user != null && user.community._id == result.user.community) {
                            var temp = new SystemMessage();
                            temp.toUser = result.user._id;
                            temp.content.questionDesc = '';
                            temp.content.replyDesc = input.desc;
                            temp.content.title = user.nickName;
                            temp.content.contentId = question._id;
                            temp.content.contentType = 'myFollowupUser';
                            temp.content.questionCreatedBy = question.createdBy;
                            temp.category = 'question';
                            temp.fromUser = user._id;
                            temp.save();

                            users.push(result.user._id);
                        }
                    });

                    //个推
                    var content = {
                        type: 1,
                        flag: 1,
                        openType: 1,
                        contentId: question._id,
                        createdBy: question.createdBy,
                        desc: user.nickName + ':' + question.desc
                    };
                    var pushData = {
                        uList: users,
                        content: content,
                        type: 'user'
                    };
                    toolUtil.putMessageGetuiPushMQ(pushData);
                }
                callbackInner(null, 1);
            });
        },
        //统计
        function (callbackInner) {
            if (tags == null) {
                tags = ['全部']
            } else {
                tags.push('全部')
            }
            Dic.find({'value': {'$in': tags}, 'category': '02'}, '_id', function (err, res) {
                res.forEach(function (tag) {
                    QuestionAndReplyCount.findOne({
                        'community': question.community,
                        'tag': tag
                    }, function (err, qc) {
                        if (qc == null) {
                            var temp = new QuestionAndReplyCount();
                            temp.questionCount = 1;
                            temp.community = question.community;
                            temp.tag = tag;
                            temp.save();
                        } else {
                            qc.questionCount += 1;
                            qc.save();
                        }
                    })
                })
            });
            //redis统计
            if (question.category != null)
                redisClient.hincrby('q:count:' + question.community, question.category + 'QuestionCount', 1);
            callbackInner(null, 1);
        },
        function (callbackInner) {   //建立索引
            var temp = new ugcIndex();
            temp.ugcId = question._id;
            temp.category = input.category;
            temp.community = question.community;
            temp.createdBy = question.createdBy;
            if (tag != null)
                temp.tag = tag;
            temp.save(callbackInner);
        },
        function (callbackInner) {
            if (pushFlag == 'activity') {
                Question.findOne({community: user.community._id, fromFlag: 'service'}, function (err, result) {
                    var content = {
                        type: 1,
                        flag: 2,
                        openType: 1,
                        contentId: result._id,
                        createdBy: result.createdBy,
                        desc: result.desc
                    };
                    var pushData = {
                        uList: [user._id],
                        content: content,
                        tag: '话题',
                        type: 'operate'
                    };
                    toolUtil.putMessageGetuiPushMQ(pushData);
                });
            }
            callbackInner();
        }
    ])
};

/**
 * 增加提问
 */
exports.postQuestionService = function (token, input, callback) {
    var nickName;

    async.waterfall([
            function (callbackInner) {
                Users.findOne({'_id': toolUtil.getUserObjIdByToken(token)}, function (err, result) {
                    Dic.findOne({'value': '全部', 'category': '02'}, '_id', function (err, res) {
                        QuestionAndReplyCount.findOne({
                            'community': result.community,
                            'tag': res
                        }, '', function (err, qc) {
                            if (qc == null) {
                                var temp = new QuestionAndReplyCount();
                                temp.questionCount = 1;
                                temp.community = result.community;
                                temp.tag = res;
                                temp.save();
                            } else {
                                qc.questionCount += 1;
                                qc.save();
                            }
                        })
                    });
                    nickName = result.nickName;
                    callbackInner(null, result);
                })
            },
            function (result, callbackInner) {
                if (result == undefined) {
                    var err = {
                        "message": 'User not found'
                    };
                    callback(err, null);
                } else {
                    restClient.get('http://' + RecommendHost + ':8002?data=' + input.desc, function (data, response) {
                        if (response.statusCode == 200) {
                            var temp = new Question();
                            temp.category = input.category;
                            temp.desc = input.desc;
                            temp.status = '未解决';
                            temp.createdBy = result._id;
                            temp.community = result.community;


                            if (data == null || data == 'unknown') {
                                temp.save(function (err, question) {
                                    callbackInner(null, question);
                                })
                            } else {
                                var sensitive = JSON.parse(data).sensitive;
                                if (sensitive != null) {
                                    temp.desc = sensitive;
                                    temp.save(function (err, question) {
                                        callbackInner(null, question);
                                    })
                                } else {
                                    var tags = [];

                                    tags = JSON.parse(data).tag;
                                    Dic.find({
                                        'value': {'$in': tags},
                                        'category': '02'
                                    }, '_id', function (err, res) {
                                        if (res == null) {
                                            temp.save(function (err, question) {
                                                callbackInner(null, question);
                                            });
                                        } else {
                                            temp.tag = res;
                                            temp.save(function (err, question) {
                                                callbackInner(null, question);
                                            });
                                            res.forEach(function (tag) {
                                                QuestionAndReplyCount.findOne({
                                                    'community': result.community,
                                                    'tag': tag
                                                }, '', function (err, qc) {
                                                    if (qc == null) {
                                                        var temp = new QuestionAndReplyCount();
                                                        temp.questionCount = 1;
                                                        temp.community = result.community;
                                                        temp.tag = tag;
                                                        temp.save();
                                                    } else {
                                                        qc.questionCount += 1;
                                                        qc.save();
                                                    }
                                                })
                                            })
                                        }
                                    })
                                }
                            }
                        } else {
                            var temp = new Question();
                            temp.category = input.category;
                            temp.desc = input.desc;
                            temp.status = '未解决';
                            temp.createdBy = result._id;
                            temp.community = result.community;

                            temp.save(function (err, question) {
                                callbackInner(null, question);
                            })
                        }
                    }).on('error', function (err) {
                        logger.error('get question tag around went wrong on the request' + err.message);

                        var temp = new Question();
                        temp.category = input.category;
                        temp.desc = input.desc;
                        temp.status = '未解决';
                        temp.createdBy = result._id;
                        temp.community = result.community;

                        temp.save(function (err, question) {
                            callbackInner(null, question);
                        })
                    });
                }
            },
            function (result, callbackInner) {
                //推送给已关注问题发起者的用户
                UserFollowups.find({'followUser': result.createdBy}, 'user', function (err, results) {
                    if (results != null && results.length > 0) {

                        var users = [];
                        results.forEach(function (user) {

                            var temp = new SystemMessage();
                            temp.toUser = user.user;
                            temp.content.questionDesc = '';
                            temp.content.replyDesc = input.desc;
                            temp.content.title = nickName;
                            temp.content.contentId = result._id;
                            temp.content.contentType = 'myFollowupUser';
                            temp.content.questionCreatedBy = result.createdBy;
                            temp.category = 'question';
                            temp.fromUser = toolUtil.getUserObjIdByToken(token);
                            temp.save();

                            users.push(user.user);
                        });


                        //个推
                        var content = {
                            type: 1,
                            flag: 1,
                            openType: 1,
                            contentId: result._id,
                            createdBy: result.createdBy,
                            desc: nickName + ':' + result.desc
                        };
                        var pushData = {
                            uList: users,
                            content: content,
                            type: 'user'
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);
                    }
                });

                //统计
                //var tag = result.tag;
                //if (tag != null) {
                //    Users.find({
                //        'community': result.community,
                //        'domainOfExpertise': result.tag
                //    }, '_id nickName domainOfExpertise images').populate('domainOfExpertise', '_id value')
                //        .exec(function (err, users) {
                //            if (users != null && users.length != 0) {
                //                async.each(users, function (user, callback) {
                //                    Question.count({'replies.repliedBy': user._id}, function (err, count) {
                //                        user._doc['totalReplied'] = count;
                //                        user._doc['totalFans'] = 70;
                //                        callback();
                //                    })
                //                }, function (err) {
                //                    if (err) {
                //                        var temp = {
                //                            "_id": result._id
                //                        };
                //                        callbackInner(null, temp);
                //                    } else {
                //                        var temp = {
                //                            "_id": result._id,
                //                            "expertList": users
                //                        };
                //                        callbackInner(null, temp);
                //                    }
                //                })
                //
                //            } else {
                //                var temp = {
                //                    "_id": result._id
                //                };
                //                callbackInner(null, temp);
                //            }
                //        })
                //} else {
                //var temp = {
                //    "_id": result._id
                //};
                //callbackInner(null, temp);
                //}

                if (input.category != null)
                    redisClient.hincrby('q:count:' + result.community, input.category + 'QuestionCount', 1);
                var temp = {
                    "_id": result._id
                };
                callbackInner(null, temp);
            }
        ],
        callback
    )
    ;
}
;

/**
 * 上传问题图片
 */
exports.setImagesToQuestion = function (questionId, images, callback) {
    Question.update({_id: questionId}, {$pushAll: {'images': images}}, callback);
};

/**
 * 修改提问
 */
exports.updateQuestionService = function (questionId, input, callback) {
    Question.update({_id: questionId}, input).exec(callback);
};

/**
 * 删除提问
 */
exports.deleteQuestionService = function (questionId, delDesc, input, callback) {
    async.series([
        function (callbackInner) {
            Question.update({_id: questionId}, {isValid: false,remark:delDesc}).exec(callbackInner);
        },
        function (callbackInner) {
            Question.findOne({'_id': questionId}, function (err, result) {

                //删除 all key
                var key = 'catch:q:all:' + result.community;
                var categoryKey = 'catch:q:category:' + result.category + ':' + result.community;
                redisClient.del(key);
                redisClient.del(categoryKey);


                var replyC = 0;
                if (result.replies != null) {
                    replyC = result.replies.length;
                }

                if (result.category != null) {
                    redisClient.hincrby('q:count:' + result.community, result.category + 'QuestionCount', -1);
                    redisClient.hincrby('q:count:' + result.community, result.category + 'ReplyCount', -replyC);
                }

                if (result.recommend) {
                    Dic.findOne({'value': '推荐', 'category': '02'}, '_id', function (err, res) {
                        QuestionAndReplyCount.findOne({
                            'community': result.community,
                            'tag': res._id
                        }, '', function (err, qc) {
                            if (qc == null) {
                                var temp = new QuestionAndReplyCount();
                                temp.questionCount = 0;
                                temp.replyCount = 0;
                                temp.community = result.community;
                                temp.tag = res;
                                temp.save();
                            } else {
                                qc.questionCount -= 1;
                                qc.replyCount -= replyC;
                                qc.save();
                            }
                        });
                    })
                }

                Dic.findOne({'value': '全部', 'category': '02'}, '_id', function (err, res) {
                    QuestionAndReplyCount.findOne({
                        'community': result.community,
                        'tag': res._id
                    }, '', function (err, qc) {
                        if (qc == null) {
                            var temp = new QuestionAndReplyCount();
                            temp.questionCount = 0;
                            temp.replyCount = 0;
                            temp.community = result.community;
                            temp.tag = res;
                            temp.save();
                        } else {
                            qc.questionCount -= 1;
                            qc.replyCount -= replyC;
                            qc.save();
                        }
                        var tags = result.tag;

                        Dic.find({'_id': {'$in': tags}, 'category': '02'}, '_id', function (err, res) {
                            if (res != null) {
                                res.forEach(function (tag) {
                                    QuestionAndReplyCount.findOne({
                                        'community': result.community,
                                        'tag': tag._id
                                    }, '', function (err, qc) {
                                        if (qc == null) {
                                            var temp = new QuestionAndReplyCount();
                                            temp.questionCount = 0;
                                            temp.replyCount = 0;
                                            temp.community = result.community;
                                            temp.tag = tag;
                                            temp.save();
                                        } else {
                                            qc.questionCount -= 1;
                                            qc.replyCount -= replyC;
                                            qc.save();
                                        }
                                    })
                                })
                            }
                            callbackInner(err, null);
                        })
                    })
                });
            })
        },
        function (callbackInner) {
            UserFollowups.remove({'question': questionId}, callbackInner)
        },
        function (callbackInner) {
            SystemMessage.remove({'content.contentId': questionId}, callbackInner);
        },
        function (callbackInner) {
            ugcIndex.remove({ugcId: questionId}, callbackInner);
        },
        function (callbackInner) {
            ugcReply.remove({ugcId: questionId}, callbackInner);
        },
        function(callbackInner){

            var arg = {
                userId: input.userId + '',
                userRole: Number(input.userRole),
                userActionType: 14
            };

            arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
            logger.debug(arg);
            scoreProxy.invoke('addScore', [arg], function (err, reply) {
                    try {
                        logger.debug(reply);
                        var data = JSON.parse(decodeURIComponent(reply));
                        if (err) {
                            logger.error('hessianInvokeAddScore-----2' + err.message);
                            callbackInner(null);
                        } else if (data.status != 0) {
                            logger.error('hessianInvokeAddScore----3' + data.status + '----' + data.msg);
                            callbackInner(null);
                        } else {
                            callbackInner(null);
                        }
                    } catch (e) {
                        logger.error('hessianInvokeAddScore---4' + e);
                        callbackInner(e);
                    }
                });

        }
    ], callback);

};


/**
 * 删除提问（自运营）
 */
exports.deleteQuestionByModerator = function (questionId, delDesc,input, callback) {
    async.series([
        function (callbackInner) {
            Question.update({_id: questionId}, {isValid: false,delDesc: delDesc}).exec(callbackInner);
        },
        function (callbackInner) {
            Question.findOne({'_id': questionId},'community category ', function (err, result) {

                //删除 all key
                var key = 'catch:q:all:' + result.community;
                var categoryKey = 'catch:q:category:' + result.category + ':' + result.community;
                redisClient.del(key);
                redisClient.del(categoryKey);


                var replyC = 0;
                if (result.replies != null) {
                    replyC = result.replies.length;
                }

                if (result.category != null) {
                    redisClient.hincrby('q:count:' + result.community, result.category + 'QuestionCount', -1);
                    redisClient.hincrby('q:count:' + result.community, result.category + 'ReplyCount', -replyC);
                }
                callbackInner();
            })
        },
        function (callbackInner) {
            UserFollowups.remove({'question': questionId}, callbackInner)
        },
        function (callbackInner) {
            SystemMessage.remove({'content.contentId': questionId}, callbackInner);
        },
        function (callbackInner) {
            ugcIndex.remove({ugcId: questionId}, callbackInner);
        },
        function (callbackInner) {
            ugcReply.remove({ugcId: questionId}, callbackInner);
        },
        function(callbackInner){

            logger.info(input.userId);
            logger.info(input.userRole);

            var arg = {
                userId: input.userId + '',
                userRole: Number(input.userRole),
                userActionType: 14
            };

            arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
            scoreProxy.invoke('addScore', [arg], function (err, reply) {
                try {
                    logger.debug(reply);
                    var data = JSON.parse(decodeURIComponent(reply));
                    if (err) {
                        logger.error('hessianInvokeAddScore-----2' + err.message);
                        callbackInner(null);
                    } else if (data.status != 0) {
                        logger.error('hessianInvokeAddScore----3 ' + data.status + '----' + data.msg);
                        callbackInner(null);
                    } else {
                        callbackInner(null);
                    }
                } catch (e) {
                    logger.error('hessianInvokeAddScore---4' + e);
                    callbackInner(e);
                }
            });

        }
    ], callback);

};

/**
 * 删除提问图片
 */
exports.deleteQuestionImagesService = function (questionId, images, callback) {
    Question.update({
        _id: questionId,
        'images.imageURL': {$in: images.images}
    }, {'$set': {'images.$.isValid': false}}).exec(callback);
};

/**
 * 举报问题
 */
exports.reportQuestionService = function (token, questionId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            QuestionReport.findOne({
                'question': questionId,
                'reportUser': user._id
            }, '', function (err, result) {
                if (err) {
                    callback(err, result);
                } else {
                    if (result == null) {
                        var temp = new QuestionReport();
                        temp.question = questionId;
                        temp.reportUser = user._id;
                        temp.save(callback);
                    } else {
                        var msg = {
                            "message": "已经举报过了"
                        };
                        callback(msg, null);
                    }
                }
            })
        }
    });
};

/**
 * ==================================回答======================================
 */

/**
 * 回答问题
 */
exports.postReplyService = function (token, questionId, input, callback) {
    var nickName;

    async.waterfall([
        function (callbackInner) {
            Users.findOne({'_id': toolUtil.getUserObjIdByToken(token)}, function (err, result) {
                callbackInner(null, result);
            })
        },
        function (result, callbackInner) {
            if (result == undefined) {
                var err = {
                    "message": 'User not found'
                };
                callback(err, null);
            } else {
                nickName = result.nickName;
                if (nickName == undefined) {
                    nickName = '有人'
                }
                var desc = input.replies.replyDesc.replace(/[\r\n]/g, "").trim();
                var rep = {
                    'replyDesc': desc,
                    'replyTo': input.replies.replyTo,
                    'repliedBy': result._id
                };
                Question.update({_id: questionId}, {$push: {'replies': rep}}).exec(function (err, result) {
                    callbackInner(null, result);
                    ugcIndex.update({ugcId: questionId}, {lastReply: new Date()}, function (err, result) {
                    });
                });
            }
        },
        function (result, callbackInner) {
            Question.findOne({
                _id: questionId,
                'isValid': true
            }).populate('createdBy', '_id community').exec(function (err, question) {
                if (question == null) {
                    var msg = {
                        "message": '这个问题已被删除'
                    };
                    callback(msg, null);
                } else {

                    var key = 'catch:q:all:' + question.community;
                    var categoryKey = 'catch:q:category:' + question.category + ':' + question.community;
                    redisClient.del(key);
                    redisClient.del(categoryKey);
                    redisClient.del('question:reply:list:' + question._id);

                    Dic.findOne({'value': '全部', 'category': '02'}, '_id', function (err, res) {
                        QuestionAndReplyCount.findOne({
                            'community': question.community,
                            'tag': res
                        }, '', function (err, qc) {
                            if (qc == null) {
                                var temp = new QuestionAndReplyCount();
                                temp.replyCount = 1;
                                temp.community = question.community;
                                temp.tag = res;
                                temp.save();
                            } else {
                                qc.replyCount += 1;
                                qc.save();
                            }
                        })
                    });
                    callbackInner(null, question);
                }
            });
        },
        function (question, callbackInner) {

            //统计回答
            if (question.tag != null) {
                question.tag.forEach(function (result) {
                    QuestionReplyStatistics.findOne({
                        'community': question.community,
                        'user': toolUtil.getUserObjIdByToken(token),
                        'tag': result
                    }, 'replyCount', function (err, res) {
                        if (res == null) {
                            var temp = new QuestionReplyStatistics();
                            temp.community = question.community;
                            temp.user = toolUtil.getUserObjIdByToken(token);
                            temp.tag = result;
                            temp.replyCount = 1;
                            temp.save();
                        } else {
                            var count = res.replyCount + 1;
                            QuestionReplyStatistics.update({
                                'community': question.community,
                                'user': toolUtil.getUserObjIdByToken(token),
                                'tag': result
                            }, {'replyCount': count}, function (err, result) {
                            })
                        }
                    });


                    QuestionAndReplyCount.findOne({
                        'community': question.community,
                        'tag': result
                    }, '', function (err, qc) {
                        if (qc == null) {
                            var temp = new QuestionAndReplyCount();
                            temp.replyCount = 1;
                            temp.community = question.community;
                            temp.tag = result;
                            temp.save();
                        } else {
                            qc.replyCount += 1;
                            qc.save();
                        }
                    })

                })
            }
            if (input.replies.replyTo != undefined) {
                Users.findOne({
                    _id: input.replies.replyTo,
                    community: question.community
                }, function (err, result) {
                    if (result != null) {
                        var temp = new SystemMessage();
                        temp.toUser = input.replies.replyTo;
                        temp.content.questionDesc = question.desc;
                        temp.content.replyDesc = input.replies.replyDesc;
                        temp.content.title = nickName;
                        temp.content.contentId = question._id;
                        temp.content.contentType = 'myReply';
                        temp.content.questionCreatedBy = question.createdBy._id;
                        temp.category = 'question';
                        temp.fromUser = toolUtil.getUserObjIdByToken(token);
                        temp.save();

                        //个推
                        var content = {
                            type: 1,
                            flag: 1,
                            openType: 1,
                            contentId: question._id,
                            createdBy: question.createdBy._id,
                            desc: nickName + '回复了你的回复'
                        };
                        var pushData = {
                            uList: [input.replies.replyTo],
                            content: content,
                            type: 'user'
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);
                    }
                });
            }
            var communityId = question.community + '';
            if (communityId == question.createdBy.community && toolUtil.getUserObjIdByToken(token) != question.createdBy._id && input.replies.replyTo == undefined) {
                var temp = new SystemMessage();
                temp.toUser = question.createdBy._id;
                temp.content.questionDesc = question.desc;
                temp.content.replyDesc = input.replies.replyDesc;
                temp.content.title = nickName;
                temp.content.contentId = question._id;
                temp.content.contentType = 'myQuestion';
                temp.content.questionCreatedBy = question.createdBy._id;
                temp.category = 'question';
                temp.fromUser = toolUtil.getUserObjIdByToken(token);
                temp.save();
            }

            if (input.replies.replyTo == undefined) {
                UserFollowups.find({'question': questionId}, 'user').populate('user', '_id community').exec(function (err, result) {
                    if (result == undefined) {
                        callbackInner(null, question);
                    } else {
                        callbackInner(null, question);

                        var users = [];
                        result.forEach(function (userId) {
                            var communityId = question.community + '';
                            if (userId.user.community == communityId && userId.user._id != toolUtil.getUserObjIdByToken(token)) {
                                var temp = new SystemMessage();
                                temp.toUser = userId.user._id;
                                temp.content.questionDesc = question.desc;
                                temp.content.replyDesc = input.replies.replyDesc;
                                temp.content.title = nickName;
                                temp.content.contentId = question._id;
                                temp.content.contentType = 'myFollowup';
                                temp.content.questionCreatedBy = question.createdBy._id;
                                temp.category = 'question';
                                temp.fromUser = toolUtil.getUserObjIdByToken(token);
                                temp.save();

                                users.push(userId.user._id);
                            }
                        });

                        //个推
                        var content = {
                            openType: 1,
                            flag: 1,
                            contentId: question._id,
                            createdBy: question.createdBy._id,
                            desc: nickName + '回复你的收藏',
                            type: 0
                        };
                        var pushData = {
                            uList: users,
                            content: content,
                            type: 'user'
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);
                    }
                })
            } else {
                callbackInner(null, question);
            }
        },
        function (question, callbackInner) {

            if (question.category != null)
                redisClient.hincrby('q:count:' + question.community, question.category + 'ReplyCount', 1);

            if (input.replies.replyTo == undefined) {
                var communityId = question.community + '';
                if (communityId == question.createdBy.community && toolUtil.getUserObjIdByToken(token) != question.createdBy._id) {

                    //个推
                    var content = {
                        type: 1,
                        openType: 1,
                        flag: 1,
                        contentId: question._id,
                        createdBy: question.createdBy._id,
                        desc: nickName + '回复了你的发布'
                    };
                    var pushData = {
                        uList: [question.createdBy._id],
                        content: content,
                        type: 'user'
                    };
                    toolUtil.putMessageGetuiPushMQ(pushData);

                }
            }
            Question.findOne({_id: questionId, 'isValid': true}).exec(function (err, result) {
                callbackInner(err, result);

                ugcReply.findOne({
                    ugcId: result._id,
                    repliedBy: toolUtil.getUserObjIdByToken(token)
                }, function (err, data) {
                    if (data == null) {
                        var temp = new ugcReply();
                        temp.ugcId = result._id;
                        temp.ugcReply = [{
                            replyId: result.replies[result.replies.length - 1]._id
                        }];
                        temp.category = result.category;
                        temp.community = result.community;
                        temp.createdBy = result.createdBy;
                        temp.repliedBy = toolUtil.getUserObjIdByToken(token);
                        temp.save();
                    } else {
                        var temp = {
                            replyId: result.replies[result.replies.length - 1]._id
                        };
                        data.ugcReply.push(temp);
                        data.lastReply = new Date();
                        data.save()
                    }
                })
            });
            Question.update({_id: questionId}, {dateLastModified: new Date()}).exec(function (err, result) {
            });
        }
    ], function (err, result) {
        callback(err, result);
    });
};

/**
 * 回复新接口
 * @param token
 * @param input
 * @param questionId
 * @param callback
 */
exports.postReplyNewService = function (token, questionId, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            if (user._id == input.replyTo) {
                input.replyTo = null;
            }
            var question;
            var replyId;
            async.series([
                function (callbackInner) {
                    Question.findOne({_id: questionId}, function (err, result) {
                        if (result == null) {
                            var msg = {
                                message: '问题不存在或已被删除'
                            };
                            callbackInner(msg, null);
                        } else {
                            question = result;
                            question._doc['huanxinName'] = user.huanxinUserName;

                            callbackInner(err, question);
                        }
                    })
                },
                function (callbackInner) {
                    var desc = input.replyDesc.replace(/[\r\n]{2,}/g, "\n").trim();
                    var rep = {
                        'replyDesc': desc,
                        'replyTo': input.replyTo,
                        'repliedBy': user._id,
                        'images': input.images
                    };
                    Question.update({_id: questionId}, {$push: {'replies': rep}}).exec(callbackInner);
                },
                function (callbackInner) {
                    Question.update({_id: questionId}, {dateLastModified: new Date()}).exec(function (err, result) {
                    });
                    ugcIndex.update({ugcId: questionId}, {lastReply: new Date()}, callbackInner);
                },
                function (callbackInner) {
                    Question.findOne({_id: questionId}, function (err, result) {
                        replyId = result.replies[result.replies.length - 1]._id;
                        callbackInner()
                    });
                },
                function (callbackInner) {
                    //统计回答
                    if (question.tag != null && question.tag.length > 0) {
                        question.tag.forEach(function (result) {
                            QuestionReplyStatistics.findOne({
                                'community': question.community,
                                'user': user._id,
                                'tag': result
                            }, 'replyCount', function (err, res) {
                                if (res == null) {
                                    var temp = new QuestionReplyStatistics();
                                    temp.community = question.community;
                                    temp.user = user._id;
                                    temp.tag = result;
                                    temp.replyCount = 1;
                                    temp.save(callbackInner);
                                } else {
                                    var count = res.replyCount + 1;
                                    QuestionReplyStatistics.update({
                                        'community': question.community,
                                        'user': user._id,
                                        'tag': result
                                    }, {'replyCount': count}, callbackInner)
                                }
                            });
                        })
                    } else {
                        callbackInner();
                    }
                },
                function (callbackInner) {
                    //if (input.replyTo != null) {
                    //    var temp = new SystemMessage();
                    //    temp.toUser = input.replyTo;
                    //    temp.content.questionDesc = question.desc;
                    //    temp.content.replyDesc = input.replyDesc;
                    //    temp.content.replyId = replyId;
                    //    temp.content.title = user.nickName;
                    //    temp.content.contentId = question._id;
                    //    temp.content.contentType = 'myReply';
                    //    temp.content.questionCreatedBy = question.createdBy;
                    //    temp.category = 'question';
                    //    temp.fromUser = user._id;
                    //    temp.save();
                    //
                    //    //个推
                    //    var content = {
                    //        type: 1,
                    //        flag: 1,
                    //        openType: 1,
                    //        contentId: question._id,
                    //        createdBy: question.createdBy,
                    //        desc: user.nickName + '回复了你的回复'
                    //    };
                    //    var pushData = {
                    //        uList: [input.replyTo],
                    //        content: content,
                    //        type: 'user'
                    //    };
                    //    toolUtil.putMessageGetuiPushMQ(pushData);
                    //}
                    callbackInner();
                },
                function (callbackInner) {
                    //if (input.replyTo == null) {
                    //    UserFollowups.find({'question': questionId}, 'user').populate('user', '_id community').exec(function (err, result) {
                    //        if (result != null) {
                    //            var users = [];
                    //            result.forEach(function (userId) {
                    //                var communityId = question.community + '';
                    //                if (userId.user.community == communityId && userId.user._id != user._id) {
                    //                    var temp = new SystemMessage();
                    //                    temp.toUser = userId.user._id;
                    //                    temp.content.questionDesc = question.desc;
                    //                    temp.content.replyDesc = input.replyDesc;
                    //                    temp.content.replyId = replyId;
                    //                    temp.content.title = user.nickName;
                    //                    temp.content.contentId = question._id;
                    //                    temp.content.contentType = 'myFollowup';
                    //                    temp.content.questionCreatedBy = question.createdBy;
                    //                    temp.category = 'question';
                    //                    temp.fromUser = user._id;
                    //                    temp.save();
                    //
                    //                    users.push(userId.user._id);
                    //                }
                    //            });
                    //
                    //            //个推
                    //            var content = {
                    //                openType: 1,
                    //                flag: 1,
                    //                contentId: question._id,
                    //                createdBy: question.createdBy,
                    //                desc: user.nickName + '回复你的收藏',
                    //                type: 0
                    //            };
                    //            var pushData = {
                    //                uList: users,
                    //                content: content,
                    //                type: 'user'
                    //            };
                    //            toolUtil.putMessageGetuiPushMQ(pushData);
                    //        }
                    //    })
                    //}
                    callbackInner();
                },
                function (callbackInner) {
                    //if (input.replyTo == null && user._id != question.createdBy) {
                    //
                    //    var temp = new SystemMessage();
                    //    temp.toUser = question.createdBy;
                    //    temp.content.questionDesc = question.desc;
                    //    temp.content.replyDesc = input.replyDesc;
                    //    temp.content.replyId = replyId;
                    //    temp.content.title = user.nickName;
                    //    temp.content.contentId = question._id;
                    //    temp.content.contentType = 'myQuestion';
                    //    temp.content.questionCreatedBy = question.createdBy;
                    //    temp.category = 'question';
                    //    temp.fromUser = user._id;
                    //    temp.save();
                    //
                    //    //个推
                    //    var content = {
                    //        type: 1,
                    //        openType: 1,
                    //        flag: 1,
                    //        contentId: question._id,
                    //        createdBy: question.createdBy,
                    //        desc: user.nickName + '回复了你的发布'
                    //    };
                    //    var pushData = {
                    //        uList: [question.createdBy],
                    //        content: content,
                    //        type: 'user'
                    //    };
                    //    toolUtil.putMessageGetuiPushMQ(pushData);
                    //}
                    callbackInner()
                },
                function (callbackInner) {
                    if (question.category != null)
                        redisClient.hincrby('q:count:' + question.community, question.category + 'ReplyCount', 1);
                    callbackInner();
                },
                function (callbackInner) {
                    Question.findOne({_id: questionId}, function (err, result) {
                        callbackInner(err, result);

                        ugcReply.findOne({ugcId: result._id, repliedBy: user._id}, function (err, data) {
                            if (data == null) {
                                var temp = new ugcReply();
                                temp.ugcId = result._id;
                                temp.ugcReply = [{
                                    replyId: result.replies[result.replies.length - 1]._id
                                }];
                                temp.category = result.category;
                                temp.community = result.community;
                                temp.createdBy = result.createdBy;
                                temp.repliedBy = user._id;
                                temp.save();
                            } else {
                                var temp = {
                                    replyId: result.replies[result.replies.length - 1]._id
                                };
                                data.ugcReply.push(temp);
                                data.lastReply = new Date();
                                data.save()
                            }
                        })
                    });
                }
            ], callback)
        }
    })
};

exports.replyAtService = function (question, replyId, uList, category, token, replyDesc) {
    async.series([
        function (callbackInner) {
            var temp = new replyAt();
            temp.replyId = replyId + '';
            temp.ugcId = question._id;
            temp.category = category;
            temp.createdBy = question.createdBy;
            temp.uList = uList;
            temp.save(callbackInner);
        },
        function (callbackInner) {
            async.eachSeries(uList, function (uId, c1) {
                Users.findOne({_id: uId}, 'huanxinUserName community', function (err, result) {
                    if (result != null) {
                        if (result.huanxinUserName.indexOf('500500') == 0) {
                            var temp = new replyAtService();
                            temp.ugcId = question._id;
                            temp.category = category;
                            temp.atUser = token;
                            temp.community = result.community;
                            temp.content = replyDesc;
                            temp.replyId = replyId;
                            temp.save(c1)

                        } else {
                            recentContact.findOne({
                                userHuanxin: question._doc.huanxinName,
                                otherHuanxin: result.huanxinUserName
                            }, function (err, data) {
                                if (data != null) {
                                    data.time = new Date();
                                    data.save(c1);
                                } else {
                                    var temp = new recentContact();
                                    temp.userHuanxin = question._doc.huanxinName;
                                    temp.otherHuanxin = result.huanxinUserName;
                                    temp.time = new Date();
                                    temp.save(c1);
                                }
                            })
                        }
                    } else {
                        c1();
                    }
                })
            }, callbackInner);
        }
    ]);
};


exports.thankReplyService = function (questionId, replyId, replyBy, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            QuestionReplyThank.findOne({'user': user._id, 'reply': replyId}, function (err, result) {
                if (result != null) {
                    var msg = {
                        "message": "你已经感谢过了"
                    };
                    callback(msg, null);
                } else {
                    Question.findOne({
                        _id: questionId,
                        'isValid': true
                    }).populate('createdBy', '_id nickName').exec(function (err, result) {
                        var tempT = new QuestionReplyThank();
                        tempT.user = user._id;
                        tempT.reply = replyId;
                        tempT.replyBy = replyBy;
                        tempT.save();

                        var nickName = user.nickName;
                        if (nickName == undefined) {
                            nickName = '有人'
                        }

                        var content = {
                            type: 1,
                            openType: 1,
                            flag: 1,
                            contentId: questionId,
                            createdBy: result.createdBy._id,
                            desc: nickName + '感谢了你'
                        };
                        var pushData = {
                            uList: [replyBy],
                            content: content,
                            type: 'user'
                        };
                        toolUtil.putMessageGetuiPushMQ(pushData);


                        callback(err, null);

                        var replies = result.replies;
                        if (replies != null) {
                            replies.forEach(function (reply) {
                                if (reply._id == replyId) {

                                    var temp = new SystemMessage();
                                    temp.toUser = reply.repliedBy;
                                    temp.content.questionDesc = result.desc;
                                    temp.content.replyDesc = '你的回复很好，非常感谢你对我的帮助';
                                    temp.content.title = nickName;
                                    temp.content.contentId = result._id;
                                    temp.content.contentType = 'myThank';
                                    temp.content.questionCreatedBy = result.createdBy._id;
                                    temp.category = 'question';
                                    temp.fromUser = user._id;
                                    temp.save(function (err, re) {
                                        if (err) {
                                            logger.error('thankReply-----' + err);
                                        }
                                    });
                                }
                            })
                        }
                    });
                }
            });
        }
    });
};

exports.getCategoryQuestionCountService = function (token, category, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            if (category == 'all') {
                var questionCount = 0;
                var replyCount = 0;
                redisClient.hkeys('q:count:' + user.community._id, function (err, fields) {
                    async.each(fields, function (field, callbackInner) {
                        redisClient.hget('q:count:' + user.community._id, field, function (err, count) {
                            if (field.indexOf('QuestionCount') != -1) {
                                questionCount += Number(count);
                            } else {
                                replyCount += Number(count);
                            }
                            callbackInner();
                        });
                    }, function (err) {
                        var data = {
                            questionCount: questionCount,
                            replyCount: replyCount
                        };
                        callback(err, data);
                    })
                });
            } else {
                var fields = [category + 'QuestionCount', category + 'ReplyCount'];
                redisClient.hmget('q:count:' + user.community._id, fields, function (err, count) {
                    if (count[0] == null && count[1] == null) {

                        if (category != 'neighbourActivity') {
                            Question.find({
                                category: category,
                                community: user.community._id,
                                isValid: true
                            }, '_id replies', function (err, results) {
                                var replyCount = 0;
                                var questionCount = 0;
                                if (results != null) {
                                    questionCount = results.length;
                                    results.forEach(function (question) {
                                        if (question.replies != null) {
                                            replyCount += question.replies.length;
                                        }
                                    });
                                }

                                redisClient.hincrby('q:count:' + user.community._id, category + 'QuestionCount', questionCount);
                                redisClient.hincrby('q:count:' + user.community._id, category + 'ReplyCount', replyCount);

                                var data = {
                                    questionCount: questionCount,
                                    replyCount: replyCount
                                };
                                callback(err, data);
                            })
                        } else {
                            neighbourActivity.find({
                                community: user.community._id,
                                isValid: true
                            }, '_id replies', function (err, results) {
                                var replyCount = 0;
                                var questionCount = 0;
                                if (results != null) {
                                    questionCount = results.length;
                                    results.forEach(function (question) {
                                        if (question.replies != null) {
                                            replyCount += question.replies.length;
                                        }
                                    });
                                }

                                redisClient.hincrby('q:count:' + user.community._id, category + 'QuestionCount', questionCount);
                                redisClient.hincrby('q:count:' + user.community._id, category + 'ReplyCount', replyCount);

                                var data = {
                                    questionCount: questionCount,
                                    replyCount: replyCount
                                };
                                callback(err, data);
                            })
                        }
                    } else {
                        var data = {
                            questionCount: Number(count[0]),
                            replyCount: Number(count[1])
                        };
                        callback(err, data);
                    }
                });
            }
        }
    });
};

/**
 * 获取小区标签问题和回复数量
 * @param token
 * @param tagId
 * @param callback
 */
exports.getCommunityQuestionAndReplyCountService = function (token, tagId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            QuestionAndReplyCount.findOne({
                'community': user.community._id,
                'tag': tagId
            }, '-_id questionCount replyCount', function (err, result) {
                if (result != null) {
                    callback(err, result);
                } else {
                    Dic.findOne({_id: tagId}, 'value', function (err, value) {

                        if (value != null) {
                            if (value.value == '全部') {
                                Question.find({
                                    'community': user.community._id,
                                    'isValid': true
                                }, '_id replies', function (err, results) {
                                    var replyCount = 0;
                                    var questionCount = results.length;
                                    if (results != null) {
                                        results.forEach(function (question) {
                                            if (question.replies != null) {
                                                replyCount += question.replies.length;
                                            }
                                        });
                                    }
                                    var temp = new QuestionAndReplyCount();
                                    temp.questionCount = questionCount;
                                    temp.replyCount = replyCount;
                                    temp.tag = tagId;
                                    temp.community = user.community._id;
                                    temp.save();
                                    var re = {
                                        "replyCount": replyCount,
                                        "questionCount": questionCount
                                    };
                                    callback(err, re);
                                })
                            } else if (value.value == '推荐') {
                                Question.find({
                                    'community': user.community._id,
                                    'isValid': true,
                                    recommend: true
                                }, '_id replies', function (err, results) {
                                    var replyCount = 0;
                                    var questionCount = results.length;
                                    if (results != null) {
                                        results.forEach(function (question) {
                                            if (question.replies != null) {
                                                replyCount += question.replies.length;
                                            }
                                        });
                                    }

                                    var temp = new QuestionAndReplyCount();
                                    temp.questionCount = questionCount;
                                    temp.replyCount = replyCount;
                                    temp.tag = tagId;
                                    temp.community = user.community._id;
                                    temp.save();
                                    var re = {
                                        "replyCount": replyCount,
                                        "questionCount": questionCount
                                    };
                                    callback(err, re);
                                })
                            } else {
                                Question.find({
                                    'community': user.community._id,
                                    'tag': tagId,
                                    'isValid': true
                                }, '_id replies', function (err, results) {
                                    var replyCount = 0;
                                    var questionCount = results.length;
                                    if (results != null) {
                                        results.forEach(function (question) {
                                            if (question.replies != null) {
                                                replyCount += question.replies.length;
                                            }
                                        });
                                    }
                                    var temp = new QuestionAndReplyCount();
                                    temp.questionCount = questionCount;
                                    temp.replyCount = replyCount;
                                    temp.tag = tagId;
                                    temp.community = user.community._id;
                                    temp.save();
                                    var re = {
                                        "replyCount": replyCount,
                                        "questionCount": questionCount
                                    };
                                    callback(err, re);
                                })
                            }
                        } else {
                            var msg = {
                                "message": "No such tag"
                            };
                            callback(msg, null);
                        }
                    });
                }
            });
        }
    });
};

/**
 *上传回答图片
 */
exports.setImagesToReply = function (questionId, replyId, images, callback) {
    Question.update({
        _id: questionId,
        'replies._id': replyId
    }, {$pushAll: {'replies.$.images': images}}, callback);
};

/**
 * 修改回答
 */
exports.updateReplyService = function (questionId, replyId, input, callback) {
    Question.update({
        _id: questionId,
        'replies._id': replyId
    }, {'replies.$.replyDesc': input.replies.replyDesc}).exec(callback);
};

/**
 * 删除回答
 */
exports.deleteReplyService = function (token, questionId, replyId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            async.series([
                function (callbackInner) {
                    Question.update({_id: questionId}, {
                        $pull: {
                            replies: {
                                _id: replyId,
                                repliedBy: user._id
                            }
                        }
                    }).exec(callbackInner);
                },
                function (callbackInner) {
                    ugcReply.update({repliedBy: user._id, ugcId: questionId}, {
                        $pull: {
                            ugcReply: {
                                replyId: replyId
                            }
                        }
                    }, callbackInner)
                },
                function (callbackInner) {
                    Question.findOne({_id: questionId}, 'category community', function (err, result) {
                        if (result.category != null)
                            redisClient.hincrby('q:count:' + result.community, result.category + 'ReplyCount', -1);
                        callbackInner();
                    })
                }
            ], callback)
        }
    })
};

/**
 * 删除回答图片
 */
exports.deleteReplyImagesService = function (questionId, replyId, images, callback) {

    Question.findOne({_id: questionId, 'isValid': true}).exec(function (err, result) {
        if (result == undefined) {
            var err = {
                "message": 'Question not found'
            };
            callback(err, null);
        } else {
            var replies = result.replies;
            var index;
            for (var i = 0; i < replies.length; i++) {
                if (replyId == replies[i]._id) {
                    index = i;
                }
            }
            var images1 = replies[index].images;
            var images2 = images.replies.images;

            for (var i = 0; i < images1.length; i++) {
                for (var j = 0; j < images2.length; j++) {
                    if (images1[i]._doc.imageURL == images2[j]) {
                        result.replies.id(replyId).images.id(images1[i]._id).isValid = false;
                        result.save(callback);
                    }
                }
            }
        }
    })
};

/**
 * 采纳回答
 */
exports.adoptReplyService = function (token, questionId, replyId, callback) {

    var replyBy;
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            Question.findOne({
                _id: questionId,
                isValid: true
            }).populate('createdBy', '_id nickName').exec(function (err, result) {
                if (result == null || result.replies == null) {
                    var msg = {
                        "message": '采纳失败'
                    };
                    callback(msg, null);
                } else {
                    var isAdopt = false;
                    result.replies.forEach(function (reply) {
                        if (reply.replyStatus == '已采纳') {
                            var msg = {
                                "message": '已有采纳回复'
                            };
                            isAdopt = true;
                            callback(msg, null);
                        }
                    });

                    if (!isAdopt) {
                        Question.update({_id: questionId, 'replies._id': replyId}, {
                            'status': '已解决',
                            'replies.$.replyStatus': '已采纳'
                        }).exec();

                        questionService.moveReplyToTopService(questionId, replyId);

                        result.replies.forEach(function (reply) {
                            if (reply._id == replyId) {
                                replyBy = reply.repliedBy;
                                AdoptedCount.findOne({
                                    community: result.community,
                                    user: reply.repliedBy
                                }, function (err, adopt) {
                                    if (adopt == null) {
                                        var temp = new AdoptedCount();
                                        temp.community = result.community;
                                        temp.user = reply.repliedBy;
                                        temp.adoptedCount = 1;
                                        temp.save()
                                    } else {
                                        AdoptedCount.update({
                                            community: result.community,
                                            user: reply.repliedBy
                                        }, {adoptedCount: adopt.adoptedCount + 1}).exec()
                                    }
                                });


                                var temp = new SystemMessage();
                                temp.toUser = reply.repliedBy;
                                temp.content.questionDesc = result.desc;
                                temp.content.replyDesc = '你的回复太棒了，给你个最佳';
                                temp.content.title = result.createdBy.nickName;
                                temp.content.contentId = result._id;
                                temp.content.contentType = 'myAdopt';
                                temp.content.questionCreatedBy = result.createdBy._id;
                                temp.category = 'question';
                                temp.fromUser = result.createdBy._id;
                                temp.save(function (err, re) {
                                });

                                var content = {
                                    type: 1,
                                    openType: 1,
                                    flag: 1,
                                    contentId: questionId,
                                    createdBy: result.createdBy._id,
                                    desc: result.createdBy.nickName + '觉得你的回复最佳'
                                };
                                var pushData = {
                                    uList: [reply.repliedBy],
                                    content: content,
                                    type: 'user'
                                };
                                toolUtil.putMessageGetuiPushMQ(pushData);
                            }
                        });
                        callback(null, replyBy);
                    }
                }
            })
        }
    });
};

/**
 * ==================================投票==================================
 */

/**
 * 创建投票
 */
exports.createPollService = function (token, input, callback) {
    async.waterfall([
        function (callbackInner) {
            Users.findOne({'_id': toolUtil.getUserObjIdByToken(token)}, function (err, result) {
                callbackInner(null, result);
            })
        },
        function (result, callbackInner) {
            if (result == undefined) {
                var err = {
                    "message": 'User not found'
                };
                callback(err, null);
            } else {
                var temp = new Question();
                temp.category = input.category;
                temp.desc = input.desc;
                temp.status = '进行中';
                temp.pollOptions = input.pollOptions;
                temp.createdBy = result._id;
                temp.community = result.community;
                temp.save(callbackInner);
            }
        }
    ], callback);
};


/**
 * 修改投票
 */
exports.updatePollService = function (pollId, input, callback) {
    Question.update({_id: pollId}, input).exec(callback);
};


/**
 * 投票
 */
exports.doPollService = function (pollId, input, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
            if (err) {
                callback(err, null);
            } else {
                async.waterfall([
                    function (callbackInner) {
                        Question.findOne({_id: pollId, 'isValid': true}, function (err, result) {
                            if (result == undefined || result == null) {
                                err = {
                                    "message": 'Poll not found'
                                };
                                callback(err, null);
                            } else {
                                if (result.pollUserList != null && result.pollUserList.indexOf(user._id) != -1) {
                                    err = {
                                        "message": 'You have voted'
                                    };
                                    callback(err, null);
                                } else {
                                    callbackInner(null, result);
                                }
                            }
                        })
                    },
                    function (result, callbackInner) {
                        result.pollOptions.forEach(function (poll) {
                                if (poll.optionLabel == input.pollOptions.optionLabel) {
                                    var count = result.pollOptions.id(poll._id).optionCount;
                                    if (count == undefined) {
                                        result.pollOptions.id(poll._id).optionCount = 1;
                                    } else {
                                        result.pollOptions.id(poll._id).optionCount++;
                                    }

                                    result.save(function (err, result) {
                                            if (err) {
                                                callback(err, null);
                                            } else {
                                                callbackInner(null, null)
                                            }
                                        }
                                    )
                                }
                            }
                        )
                    },
                    function (result, callbackInner) {
                        Question.update({_id: pollId}, {'$push': {'pollUserList': user._id}}, function (err, result) {
                            callbackInner(null, null);
                        })
                    },
                    function (result, callbackInner) {
                        Question.findOne({_id: pollId, 'isValid': true}, 'pollOptions', function (err, result) {
                            if (err) {
                                callback(err, null);
                            } else {
                                result._id = undefined;
                                callback(null, result);
                            }
                        })
                    }
                ], callback);
            }
        }
    )
}
;

/**
 * 关闭投票
 */
exports.closePollService = function (pollId, callback) {
    Question.update({_id: pollId}, {'status': '已关闭'}).exec(callback);
};

/**
 * 获取提问详情
 */
exports.getDetailOfQuestionOrPollService = function (token, id, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            Question.findOne({
                _id: id,
                'isValid': true
            }, '_id desc community category browserCount status tag images.imageURL images._id replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.replyType replies.displayOrder replies.dateReplied replies.repliedBy replies.replyTo pollOptions dateCreated createdBy')
                .populate('tag', 'category value _id').populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus').populate('replies.repliedBy', '_id nickName images userType authenticationStatus').populate('replies.replyTo', '_id nickName images').exec(function (err, result) {
                    if (result == null) {
                        var msg = {
                            "message": "这个问题已被删除"
                        };
                        callback(msg, null);
                    } else {
                        result.replies.sort(function (a, b) {
                            if (a.displayOrder == undefined) {
                                a.displayOrder = 0;
                            }
                            if (b.displayOrder == undefined) {
                                b.displayOrder = 0;
                            }
                            if (a.displayOrder > b.displayOrder) {
                                return -1
                            } else if (a.displayOrder < b.displayOrder) {
                                return 1
                            } else {
                                return a.dateReplied - b.dateReplied
                            }
                        });

                        var browserCount;
                        if (result.browserCount == null) {
                            browserCount = 0;
                        } else {
                            browserCount = result.browserCount + 1;
                        }
                        result.browserCount = browserCount;

                        if (result.tag == null || result.tag.length == 0) {
                            result.tag = undefined;
                        }

                        async.each(result.replies, function (reply, callback) {
                            if (reply.replyTo == null) {
                                reply.replyTo = undefined;
                            }
                            reply.displayOrder = undefined;

                            QuestionReplyPraise.find({'reply': reply._id}, '', function (err, resPra) {
                                if (resPra == null) {
                                    reply._doc['praiseCount'] = 0
                                } else {
                                    reply._doc['praiseCount'] = resPra.length;
                                    reply._doc['isPraise'] = 'No';
                                    resPra.forEach(function (res) {
                                        if (res.user == user._id) {
                                            reply._doc['isPraise'] = 'Yes'
                                        }
                                    });
                                }
                                QuestionReplyThank.findOne({
                                    'reply': reply._id,
                                    'user': result.createdBy._id
                                }, function (err, result) {
                                    if (result == null) {
                                        reply._doc['isThank'] = 'No'
                                    } else {
                                        reply._doc['isThank'] = 'Yes'
                                    }
                                    callback();
                                });
                            });
                        }, function (err) {
                            if (err) {
                                callback(err, null);
                            } else {
                                Question.update({_id: id}, {'browserCount': browserCount}, function (err, re) {
                                    UserFollowups.findOne({
                                        'user': user._id,
                                        'question': id
                                    }, function (err, userFollowup) {
                                        if (err || userFollowup == null) {
                                            result._doc['followup'] = 'No'
                                        } else {
                                            result._doc['followup'] = 'Yes'
                                        }
                                        callback(err, result);
                                    });
                                });
                            }
                        });
                    }
                });
        }
    })
};

exports.getDetailOfQuestionService = function (token, id, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            Question.findOne({
                _id: id,
                'isValid': true
            }, '_id isShow acrossCity desc community category browserCount status tag images.imageURL images._id  dateCreated createdBy displayOrder level categoryOrder topBeginDate topEndDate')
                .populate('tag', 'category value _id').populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit').exec(function (err, result) {
                    if (result == null) {
                        var msg = {
                            "message": "这个问题已被删除"
                        };
                        callback(msg, null);
                    } else {

                        //设置屏蔽 赋值-1
                        logger.info("设置屏蔽值中");
                        if(result.isShow&&result.isShow == -1) {
                            result._doc["isShield"]= true;
                        }else {
                            result._doc["isShield"]= false;
                        }
                        var browserCount;
                        if (result.browserCount == null) {
                            browserCount = 0;
                        } else {
                            browserCount = result.browserCount + 1;
                        }
                        result.browserCount = browserCount;
                        result._doc['browserCountStr'] = toolUtil.transformNumber(browserCount);

                        if (result.tag == null || result.tag.length == 0) {
                            result.tag = undefined;
                        }

                        if (result.createdBy.showUnit != null && !result.createdBy.showUnit) {
                            result.createdBy.roomUnit = undefined;
                        }

                        if(result.topBeginDate&&result.topEndDate&&result.topBeginDate<= moment()&&moment() <= result.topEndDate)
                        {
                            result._doc['isTop'] = true;
                        }else
                        {
                            result._doc['isTop'] = false;
                        }
                        result._doc['isPrime'] = result.level == 1;

                        result.createdBy.showUnit = undefined;

                        Question.update({_id: id}, {'browserCount': browserCount}, function (err, re) {
                            UserFollowups.findOne({
                                'user': user._id,
                                'question': id
                            }, function (err, userFollowup) {
                                if (err || userFollowup == null) {
                                    result._doc['followup'] = 'No'
                                } else {
                                    result._doc['followup'] = 'Yes'
                                }
                                callback(err, result);
                                /***
                                 * isAllTop 已不再使用
                                 */
                                //ugcIndex.findOne({ugcId: id}, function (err, index) {
                                //
                                //    result._doc['isTopAll'] = index.displayOrder ? true : false;
                                //    callback(err, result);
                                //});

                            });
                        });

                    }
                });
        }
    });
};

exports.getDetailReplyOfQuestionService = function (page, token, id, vcode, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var data = [];
            Question.findOne({
                _id: id,
                'isValid': true
            }, 'createdBy replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.replyType replies.displayOrder replies.dateReplied replies.repliedBy replies.replyTo')
                .populate('createdBy', '_id nickName images userType authenticationStatus').populate('replies.repliedBy', '_id nickName images userType authenticationStatus showUnit roomUnit').populate('replies.replyTo', '_id nickName images').exec(function (err, result) {
                    if (result == null || result.replies == null) {
                        callback(null, data);
                    } else {
                        result.replies.sort(function (a, b) {
                            if (a.displayOrder == undefined) {
                                a.displayOrder = 0;
                            }
                            if (b.displayOrder == undefined) {
                                b.displayOrder = 0;
                            }
                            //if (a.displayOrder > b.displayOrder) {
                            //    return -1
                            //} else if (a.displayOrder < b.displayOrder) {
                            //    return 1
                            //} else {
                            //    return a.dateReplied - b.dateReplied
                            //}
                            if (a.dateReplied > b.dateReplied) {
                                return -1
                            } else if (a.dateReplied < b.dateReplied) {
                                return 1
                            }
                            else {
                                return a.dateReplied - b.dateReplied
                            }
                        });

                        async.each(result.replies, function (reply, callback1) {

                            if (reply.repliedBy.showUnit != null && !reply.repliedBy.showUnit) {
                                reply.repliedBy.roomUnit = undefined;
                            }
                            reply.repliedBy.showUnit = undefined;

                            if (reply.replyTo == null) {
                                reply.replyTo = undefined;
                            }
                            reply.displayOrder = undefined;

                            QuestionReplyPraise.find({'reply': reply._id}, '', function (err, resPra) {
                                if (resPra == null) {
                                    reply._doc['praiseCount'] = 0
                                } else {
                                    reply._doc['praiseCount'] = resPra.length;
                                    reply._doc['isPraise'] = 'No';
                                    resPra.forEach(function (res) {
                                        if (res.user == user._id) {
                                            reply._doc['isPraise'] = 'Yes'
                                        }
                                    });
                                }
                                QuestionReplyThank.findOne({
                                    'reply': reply._doc._id,
                                    'user': result.createdBy._id
                                }, function (err, result) {
                                    if (result == null) {
                                        reply._doc['isThank'] = 'No'
                                    } else {
                                        reply._doc['isThank'] = 'Yes'
                                    }

                                    if (reply.replyDesc.indexOf(atFlag) != -1) {

                                        replyAt.findOne({replyId: reply._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                if (vcode < 1500) {
                                                    at.uList.forEach(function (temp, i) {
                                                        reply.replyDesc = reply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                    });
                                                } else {
                                                    reply._doc['uList'] = at.uList;
                                                }
                                            }
                                            callback1(err, null);
                                        }).populate('uList', '_id nickName');
                                    } else {
                                        callback1()
                                    }
                                });
                            });
                        }, function (err) {
                            if (err) {
                                callback(err, null);
                            } else {
                                page = Number(page);
                                var replies = result.replies.slice(page * listPageSize, (page + 1) * listPageSize);
                                var temp = {
                                    replyCount: result.replies.length,
                                    replyCountStr: toolUtil.transformNumber(result.replies.length),
                                    replies: replies
                                };
                                callback(null, temp);
                            }
                        });
                    }
                });
        }
    });
};


/**
 * 回复点赞
 */
exports.praiseReplyService = function (replyId, replyBy, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            QuestionReplyPraise.findOne({
                'reply': replyId,
                'user': user._id
            }, '', function (err, result) {
                if (err) {
                    callback(err, result);
                } else {
                    if (result == null) {
                        var temp = new QuestionReplyPraise();
                        temp.reply = replyId;
                        temp.user = user._id;
                        temp.replyBy = replyBy;
                        temp.save(callback);
                    } else {
                        var msg = {
                            "message": "无法重复点赞"
                        };
                        callback(msg, null);
                    }
                }
            })
        }
    });
};

/**
 * 获取我所提的问题和投票列表
 */
exports.getMyQuestionAndPollListService = function (page, token, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {

            var index = Number(page) * listPageSize;
            var userId = user._id;

            Question.find({
                'createdBy': userId,
                community: user.community._id,
                'isValid': true
            }, '_id desc community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category tag images replies dateCreated createdBy')
                .skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callbackInner(msg, null);
                    } else {
                        results.forEach(function (question) {
                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;
                                question.replies.forEach(function (reply) {
                                    if (reply.replyStatus == '已采纳') {
                                        question._doc['adoptedReply'] = reply;
                                    }
                                });
                            }
                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }

                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }
                            question._doc.replies = undefined;
                        });
                        callback(null, results);
                    }
                })

        }
    })
};

/**
 * 获取我的问题列表（新）
 * @param page
 * @param token
 * @param callback
 */
exports.getMyQuestionListService = function (page, token, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        var index = Number(page) * listPageSize;
        var data = [];

        ugcIndex.find({community: user.community._id, createdBy: user._id}).skip(index).limit(listPageSize).sort({
            dateCreated: -1
        }).exec(function (err, result) {
            if (result != null) {
                async.eachSeries(result, function (ugc, callbackInner) {
                    if (ugc.category == 'neighbourActivity') {
                        neighbourActivity.findOne({_id: ugc.ugcId}, '_id title replies.replyStatus replies.images replies._id replies.replyDesc  replies.dateReplied replies.repliedBy desc category dateCreated createdBy')
                            .populate('tag', 'category value _id')
                            .populate('replies.repliedBy', '_id nickName images')
                            .populate('createdBy', '_id nickName images')
                            .exec(function (err, activity) {
                                if (activity != null) {

                                    if (activity.replies != null) {
                                        activity._doc['numberOfReplies'] = activity.replies.length;
                                        activity.replies.forEach(function (reply) {
                                            if (reply.replyStatus == '已采纳') {
                                                activity._doc['adoptedReply'] = reply;
                                            }
                                        });
                                    }

                                    activity._doc.replies = undefined;

                                    if (activity._doc.adoptedReply != null && activity._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                                        replyAt.findOne({replyId: activity._doc.adoptedReply._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                at.uList.forEach(function (temp, i) {
                                                    activity._doc.adoptedReply.replyDesc = activity._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                });
                                            }
                                            data.push(activity);
                                            callbackInner()
                                        }).populate('uList', '_id nickName');
                                    } else {
                                        data.push(activity);
                                        callbackInner(err);
                                    }
                                } else {
                                    callbackInner(err);
                                }
                            })
                    } else {
                        Question.findOne({
                            _id: ugc.ugcId,
                            'isValid': true
                        }, '_id desc replies.replyStatus replies._id replies.replyDesc replies.images replies.dateReplied replies.repliedBy category replies dateCreated createdBy')
                            .populate('replies.repliedBy', '_id nickName images')
                            .populate('createdBy', '_id nickName images').exec(function (err, question) {
                                if (question != null) {
                                    if (question.replies != null) {
                                        question._doc['numberOfReplies'] = question.replies.length;
                                        question.replies.forEach(function (reply) {
                                            if (reply.replyStatus == '已采纳') {
                                                question._doc['adoptedReply'] = reply;
                                            }
                                        });
                                    }

                                    question._doc.replies = undefined;

                                    if (question._doc.adoptedReply != null && question._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                                        replyAt.findOne({replyId: question._doc.adoptedReply._id + ''}, function (err, at) {
                                            if (at != null && at.uList != null) {
                                                at.uList.forEach(function (temp, i) {
                                                    question._doc.adoptedReply.replyDesc = question._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                });
                                            }
                                            data.push(question);
                                            callbackInner()
                                        }).populate('uList', '_id nickName');
                                    } else {
                                        data.push(question);
                                        callbackInner(err);
                                    }
                                } else {
                                    callbackInner();
                                }
                            })
                    }
                }, function (err) {
                    callback(err, data);
                })
            } else {
                callback(null, []);
            }
        });
    })
};

exports.getMyReplyListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            var index = Number(page) * listPageSize;
            var data = [];

            ugcReply.find({
                community: user.community._id,
                repliedBy: user._id,
                ugcReply: {$not: {$size: 0}}
            }).skip(index).limit(listPageSize)
                .sort('-lastReply')
                .exec(function (err, result) {
                    if (result != null) {
                        async.eachSeries(result, function (ugc, callbackInner) {
                            if (ugc.category == 'neighbourActivity') {
                                neighbourActivity.findOne({_id: ugc.ugcId}, '_id title replies.replyStatus replies._id replies.images replies.replyDesc replies.dateReplied replies.repliedBy desc category dateCreated createdBy')
                                    .populate('tag', 'category value _id')
                                    .populate('replies.repliedBy', '_id nickName images')
                                    .populate('createdBy', '_id nickName images')
                                    .exec(function (err, activity) {
                                        if (activity != null) {

                                            if (activity.replies != null) {
                                                activity._doc['numberOfReplies'] = activity.replies.length;
                                                activity.replies.forEach(function (reply) {
                                                    if (user._id == reply.repliedBy._id) {
                                                        activity._doc['myReply'] = reply;
                                                    }
                                                });
                                            }
                                            activity._doc.replies = undefined;

                                            if (activity._doc.myReply != null && activity._doc.myReply.replyDesc.indexOf(atFlag) != -1) {
                                                replyAt.findOne({replyId: activity._doc.myReply._id + ''}, function (err, at) {
                                                    if (at != null && at.uList != null) {
                                                        at.uList.forEach(function (temp, i) {
                                                            activity._doc.myReply.replyDesc = activity._doc.myReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                        });
                                                    }
                                                    data.push(activity);
                                                    callbackInner()
                                                }).populate('uList', '_id nickName');
                                            } else {
                                                data.push(activity);
                                                callbackInner(err);
                                            }
                                        } else {
                                            callbackInner(err);
                                        }
                                    })
                            } else {
                                Question.findOne({
                                    _id: ugc.ugcId,
                                    'isValid': true
                                }, '_id desc replies.replyStatus replies._id replies.replyDesc replies.images replies.dateReplied replies.repliedBy category replies dateCreated createdBy')
                                    .populate('replies.repliedBy', '_id nickName images')
                                    .populate('createdBy', '_id nickName images').exec(function (err, question) {
                                        if (question != null) {
                                            if (question.replies != null) {
                                                question._doc['numberOfReplies'] = question.replies.length;
                                                question.replies.forEach(function (reply) {
                                                    if (user._id == reply.repliedBy._id) {
                                                        question._doc['myReply'] = reply;
                                                    }
                                                });
                                            }
                                            question._doc.replies = undefined;

                                            if (question._doc.myReply != null && question._doc.myReply.replyDesc.indexOf(atFlag) != -1) {
                                                replyAt.findOne({replyId: question._doc.myReply._id + ''}, function (err, at) {
                                                    if (at != null && at.uList != null) {
                                                        at.uList.forEach(function (temp, i) {
                                                            question._doc.myReply.replyDesc = question._doc.myReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                        });
                                                    }
                                                    data.push(question);
                                                    callbackInner()
                                                }).populate('uList', '_id nickName');
                                            } else {
                                                data.push(question);
                                                callbackInner(err);
                                            }
                                        } else {
                                            callbackInner();
                                        }
                                    })
                            }
                        }, function (err) {
                            callback(err, data);
                        })
                    } else {
                        callback(null, []);
                    }
                });
        }
    })
};

/**
 * 获取我参与回答的问题列表
 */
exports.getMyRepliedQuestionListService = function (page, token, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            var index = Number(page) * listPageSize;
            var userId = user._id;

            Question.find({
                'createdBy': {'$ne': userId},
                'replies.repliedBy': userId,
                community: user.community._id,
                'isValid': true
            }, '_id desc community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category tag images replies dateCreated createdBy')
                .skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callbackInner(msg, null);
                    } else {
                        results.forEach(function (question) {
                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;

                                if (userId != question.createdBy._id) {
                                    question.replies.forEach(function (reply) {
                                        if (userId == reply.repliedBy._id) {
                                            question._doc['myReply'] = reply;
                                        }
                                    });
                                }
                            }
                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }

                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }
                            question._doc.replies = undefined;
                        });
                        callback(null, results);
                    }
                })
        }
    })
};

/**
 * 问题置顶
 */
exports.moveQuestionToTopService = function (opt, callback) {

    var option={};
    if(opt.communityId) option.community = opt.communityId;
    // if(opt.category) option.category = opt.category;
    option['topBeginDate'] ={$lte: moment().format('YYYY-MM-DD HH:mm:ss')};
    option['topEndDate'] = {$gte:moment().format('YYYY-MM-DD HH:mm:ss')};
    /*  宝宝树66小区二次改造    mod   chenf  20170814  start   */
    option['topFlg'] = 2;
    /*  宝宝树66小区二次改造    mod   chenf  20170814  end   */
    logger.debug(option);
    Question.find(option).exec(function (err, result) {
        if(result.length) {
            logger.debug(result);
            if(opt.type == '1') {
                async.series([
                    function (callbackInner) {
                        //取消其他置顶
                        var data = {
                            topEndDate: moment()
                        };
                        Question.update({_id: opt.questionId}, data, callbackInner);
                    },
                    function (callbackInner) {

                        var data = {
                            topBeginDate: moment()
                            , topEndDate: moment().add(1, 'day')
                        };
                        Question.update({_id: opt.questionId}, data, callbackInner);
                    }

                ], callback);
            }else{
                callback({message:'已经存在一个置顶帖子了哦'},{})
            }
        }else{
            logger.debug('Top');

            async.series([

                function (callbackInner) {
                    var data = {
                        topBeginDate: moment()
                        , topEndDate: moment().add(1, 'day')
                        /*  宝宝树66小区二次改造    mod   chenf  20170814  start   */
                        ,topFlg:2
                        /*  宝宝树66小区二次改造    mod   chenf  20170814  end   */
                    };
                    Question.update({_id: opt.questionId}, data, callbackInner);
                },
                /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  start   */
                function (callbackInner) {
                    var userId =  opt.userId;
                    // top:置顶
                    // 置顶永远+1
                    userService.incModeratorManager(userId, 'top', 1, callbackInner);
                },
                function (callbackInner) {
                    var userId =  opt.userId;
                    var questionId = opt.questionId;
                    userService.saveModeratorManagerOperationNote(userId, questionId, '置顶', null);
                },
                /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  end   */
                function (callbackInner) {

                    var body = {
                        user_id : opt.userId
                        ,action : 'top'
                        ,action_id : opt.questionId
                    };
                    logger.debug(body);
                    var sql = "insert into 66xiaoqu_log.user_action_log set ?";
                    mysqlUtil.queryBI(sql, [body], function (err, result) {
                        callbackInner(err, result);
                    });

                }
            ], callback);
        }

    });

    //var Num = 0;
    //logger.info(opt);
    //async.series([
    //    function (callbackInner) {
    //        if (opt.category != null) {
    //            Question.find({
    //                community: opt.communityId,
    //                isValid: true,
    //                category: opt.category
    //            }).sort({categoryOrder: -1}).limit(3)
    //                .exec(function (err, results) {
    //                    Num = (results[0].categoryOrder ? results[0].categoryOrder : 0) + 1;
    //                    if (results.length == 3 && results[2].categoryOrder > 0) {
    //                        results[2].categoryOrder = undefined;
    //                        results[2].save(callbackInner);
    //                    } else {
    //                        callbackInner(null, null);
    //                    }
    //                });
    //        } else {
    //            Question.find({
    //                community: opt.communityId,
    //                isValid: true
    //            }).sort({allOrder: -1}).limit(3)
    //                .exec(function (err, results) {
    //                    Num = (results[0].allOrder ? results[0].allOrder : 0) + 1;
    //                    if (results.length == 3 && results[2].allOrder > 0) {
    //                        results[2].allOrder = undefined;
    //                        results[2].save(callbackInner);
    //                    } else {
    //                        callbackInner(null, null);
    //                    }
    //                });
    //        }
    //    },
    //    function (callbackInner) {
    //        if (opt.category != null) {
    //            Question.update({_id: opt.questionId}, {categoryOrder: Num}).exec(callbackInner);
    //        } else {
    //            Question.update({_id: opt.questionId}, {allOrder: Num}).exec(callbackInner);
    //        }
    //    }
    //], callback)
};

/**
 * 取消置顶
 */
exports.cancelTopQuestionService = function (opt, callback) {

    console.log(opt);
    var data ={
        topBeginDate : null,
        topEndDate : null
        /*  宝宝树66小区二次改造    mod   chenf  20170814  start   */
        ,topFlg : 0
        /*  宝宝树66小区二次改造    mod   chenf  20170814  end   */
    };
    Question.update({_id:opt.questionId}, data, callback);

    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  start   */
    var userId =  opt.userId;
    var questionId =  opt.questionId;
    // top:置顶
    userService.saveModeratorManagerOperationNote(userId, questionId, '取消置顶', null);
    // 当前时间-6小时
    var dateCreated = moment().subtract(6, "hours").format("YYYY-MM-DD HH:mm:ss");
    var option = {'user': userId, 'question': questionId, 'operationType': '置顶', 'dateCreated': {'$gt': dateCreated}};
    // 如果当前大使对当前帖子6小时内有置顶操作的话,则置顶数-1(取消置顶)
    ModeratorManagerOperationNote.find(option, {'_id': 1}).sort({'dateCreated' : -1}).limit(1).exec(function (err, result) {
        if(result != null && result.length > 0) {
            userService.incModeratorManager(userId, 'top', -1, null);
        }
    });
    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  end   */

    //if (input.category != null) {
    //    Question.findOne({_id: input.questionId}, function (err, result) {
    //        result.categoryOrder = undefined;
    //        result.save(callback);
    //    })
    //} else {
    //    Question.findOne({_id: input.questionId}, function (err, result) {
    //        result.allOrder = undefined;
    //        result.save(callback);
    //    })
    //}
};

/**
 * 回复置顶
 */
exports.moveReplyToTopService = function (questionId, replyId, callback) {
    async.waterfall([
        function (callbackInner) {
            Question.findOne({_id: questionId, 'isValid': true}).exec(function (err, result) {
                callbackInner(null, result);
            })
        },
        function (result, callbackInner) {
            if (result == null) {
                var msg = {
                    "message": 'No such question'
                };
                callbackInner(msg, null);
            } else {
                var replies = result.replies;
                replies.sort(function (a, b) {
                    return a.displayOrder > b.displayOrder ? -1 : 1;
                });
                var maxValue;

                if (replies[0]._doc.displayOrder == undefined) {
                    maxValue = 1;
                } else {
                    maxValue = replies[0]._doc.displayOrder + 1;
                }
                Question.update({
                    _id: questionId,
                    'replies._id': replyId
                }, {'replies.$.displayOrder': maxValue}).exec(callbackInner);
            }
        }
    ], callback)
};

/**
 * 获取推荐给我的问题和投票列表
 */
exports.getRecommendedQuestionAndPollListService = function (token, page, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {

            //restClient.get('http://localhost:8003?userid=' + user._id, function (data, response) {
            //    var ids = data.ids;
            //
            //    Question.find({_id: {$in: ids}})
            //}).on('error', function (err) {
            //
            //});

            Question.find({
                'community': user.community._id,
                recommend: true,
                'isValid': true
            }, '_id desc displayOrder browserCount community category status tag images replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy pollOptions pollUserList dateCreated createdBy')
                .populate('tag', 'category value _id').populate('replies.repliedBy', '_id nickName images')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {

                            //计算问题回复数量
                            var replyCount = 0;

                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;
                                replyCount = question.replies.length;
                                question.replies.forEach(function (reply) {
                                    if (reply.replyStatus == '已采纳') {
                                        question._doc['adoptedReply'] = reply;
                                    }
                                })
                            }

                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }
//=================================================================================
//                            if (question.browserCount >= 200) {
//                                question._doc['hot'] = true;
//                            } else {
//                                question._doc['hot'] = false;
//                            }
//
//                            var ranking;
//                            var diffDay = moment().diff(moment(question.dateCreated), 'days')
//                            if (diffDay == 0) {
//                                ranking = 0.1 * 0.5
//                            } else if (diffDay > 0 && diffDay < 7) {
//                                ranking = 0.1 * 0.3
//                            } else {
//                                ranking = 0.1 * 0.2
//                            }
//
//                            ranking += 0.1 * (replyCount > 10) ? 0.8 : 0.2;
//
//                            if (question.browserCount > 100) {
//                                ranking += 0.2 * 0.6
//                            } else if (question.browserCount > 10 && question.browserCount <= 100) {
//                                ranking += 0.2 * 0.3
//                            } else {
//                                ranking += 0.2 * 0.1
//                            }
//
//                            if (question._doc.adoptedReply == null) {
//                                ranking += 0.15
//                            }
//
//
//                            if (question._doc.tag != null) {
//                                Users.findOne({_id: user._id}, 'hobbies', function (err, result) {
//                                    if (result.hobbies.indexOf(question._doc.tag) > -1) {
//                                        ranking += 0.3
//                                    }
//                                })
//                            }
//                            question._doc['ranking'] = ranking;
//                            results.sort(function (a, b) {
//                                return b._doc.ranking - a._doc.ranking
//                            });
//
//                            results.forEach(function (result) {
//                                result._doc.ranking = undefined;
//                            });
//                            results = results.splice(0, 20);

                            //过滤tag为null的问题
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }
                            question._doc.replies = undefined;
                            question._doc.pollUserList = undefined;

                        });

                        results.sort(function (a, b) {
                            if (a.displayOrder == undefined) {
                                a.displayOrder = 0;
                            }
                            if (b.displayOrder == undefined) {
                                b.displayOrder = 0;
                            }
                            if (a.displayOrder > b.displayOrder) {
                                return -1
                            } else if (a.displayOrder < b.displayOrder) {
                                return 1
                            } else {
                                return b.dateCreated - a.dateCreated
                            }
                        });

                        var data = results.slice(page * listPageSize, (page + 1) * listPageSize);

                        callback(null, data);
                    }
                })
        }
    })
};

/**
 * 获取有采纳回答的问题
 * @param communityId
 * @param callback
 */
exports.getQuestionByAdoptedReplyService = function (communityId, callback) {
    Question.find({
        'community': communityId,
        'replies.replyStatus': '已采纳',
        'isValid': true
    }, '_id desc displayOrder browserCount community category tag images replies.replyStatus replies._id replies.replyDesc replies.dateReplied replies.repliedBy dateCreated createdBy')
        .populate('tag', 'category value _id').populate('replies.repliedBy', '_id nickName images')
        .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-dateCreated').limit(20).exec(function (err, results) {
            if (results == undefined || results == null) {
                var msg = {
                    "message": 'get err'
                };
                callback(msg, null);
            } else {
                results.forEach(function (question) {
                    if (question.replies != null) {
                        question._doc['numberOfReplies'] = question.replies.length;
                        question.replies.forEach(function (reply) {
                            if (reply.replyStatus == '已采纳') {
                                question._doc['adoptedReply'] = reply;
                            }
                        })
                    }
                    question.replies = undefined;
                    if (question.browserCount == null) {
                        question.browserCount = 0;
                    }
                    if (question._doc.tag == null || question._doc.tag.length == 0) {
                        question._doc.tag = undefined;
                    }
                });
                callback(null, results);
            }
        });
};

/**
 * 获取小区所有问题列表
 */
exports.getAllCommunityQuestionListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var communityId = user.community._id;
            var index = Number(page) * listPageSize;
            var date = new Date();

            Question.find({
                'community': communityId,
                'isValid': true
            }, '_id desc allOrder community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy').skip(index).limit(listPageSize)
                .populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit').sort({
                    allOrder: -1,
                    dateLastModified: -1
                }).exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {
                            //计算问题回复数量
                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;

                                question.replies.forEach(function (reply) {
                                    if (reply.replyStatus == '已采纳') {
                                        question._doc['adoptedReply'] = reply;
                                    }
                                })
                            }
                            question._doc.replies = undefined;
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }

                            //置顶标识
                            question._doc['isTop'] = question._doc.allOrder ? true : false;
                            question._doc.allOrder = undefined;

                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }

                            if (question.dateLastModified > date) {
                                question.dateLastModified = question.dateCreated;
                            }

                            question._doc['categoryName'] = questionCategory[question.category];

                            if (question.createdBy.showUnit != null && !question.createdBy.showUnit) {
                                question.createdBy.roomUnit = undefined;
                            }
                            question.createdBy.showUnit = undefined;
                        });
                        callback(null, results);
                    }
                })
        }
    });
};

/**
 * 获取互助全部列表
 * @param ts
 * @param token
 * @param sortName
 * @param callback
 */
// 2015-10-20
exports.getAllCommunityQuestionListNewService = function (ts, token, level,opt_param,flag,communityId, callback) {
    var communityId=communityId;
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            var date = ts == '0' ? new Date() : new Date(Number(ts));

            var opt = {};
            if(opt_param)
            {
                opt = opt_param;
            }
            //if (ts != '0') {
            //    opt.displayOrder = null;
            //}
            <!--  宝宝树66小区二次改造    add   gct  20170808   start   -->
            if("0"==flag)
            {
                opt.community = user.community._id;
            }
            else
            {
                opt.community=communityId;
            }
            <!--  宝宝树66小区二次改造    add   gct  20170808   end   -->

            if (level != null) {
                opt['$or'] = [{level: 1}, {category: {$in: ['question', 'share', 'essence']}}]
            }


            opt['dateCreated'] = {$lt: date};

            var sort = {
                //topBeginDate:-1,
                //topEndDate:-1
                dateCreated:-1
            };
            sort['dateCreated'] = -1;
            var repliesStatus = opt.replyStatus;
            console.log("筛选已经采纳的情况");
            delete opt.replyStatus;
            logger.info(repliesStatus);
            opt.isValid = true;

            var topIndex = -1;
            var index = -1;
            var isReplied = false;
            var data = [];

            /****
             * 被举报的帖子列表
             * @type {boolean} 判断是否筛选出举报帖子，忽视其他条件
             */
            var isReported = opt.isReported;
            delete opt.isReported;

            if(isReported) {
                <!--  宝宝树66小区三次改造    mod   guo.xiaomin  20171016  start   -->
                // questionService.getReportedQuestionList(opt['dateCreated'],sort,callback); // 旧
                questionService.getReportedQuestionList(opt['dateCreated'],sort,communityId,callback); // 新
                <!--  宝宝树66小区三次改造    mod   guo.xiaomin  20171016  end   -->
            }
            else {
                async.waterfall([function(callbackInner) {
                    Community.findOne({_id:opt.community},'communityType').exec(function(err,result)
                    {
                        logger.debug(result);
                        if(result.communityType == 0){
                            delete  opt.community;
                        }
                        callbackInner(null,opt);
                    });
                },function(argv,callbackInner) {
                    Question.find(argv, '_id desc topBeginDate topEndDate  browserCount replies.replyStatus replies._id level replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy category tag images replies dateCreated createdBy praiseCount')
                        .populate('tag', 'category value _id')
                        .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                        .populate('community', '_id communityName')
                        .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
                        .limit(listPageSize).sort(sort)
                        .exec(function (err, questions) {
                            async.eachSeries(questions,function(question,callbackInner) {
                                isReplied = false;
                                if (question != null && question.createdBy != null) {
                                    //计算问题回复数量
                                    if (question.replies != null) {
                                        question._doc['numberOfReplies'] = question.replies.length;
                                        question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);
                                        question.replies.forEach(function (reply) {
                                            if (reply.replyStatus == '已采纳') {
                                                question._doc['adoptedReply'] = reply;
                                                isReplied = true;
                                            }
                                        })
                                    }

                                    question._doc['isPrime'] = question.level == 1;
                                    question._doc['browserCountStr'] = toolUtil.transformNumber(question._doc.browserCount);
                                    question._doc.replies = undefined;

                                    if (question.createdBy.showUnit != null && !question.createdBy.showUnit) {
                                        question.createdBy.roomUnit = undefined;
                                    }
                                    question.createdBy.showUnit = undefined;
                                    if (question.topBeginDate && question.topEndDate && question.topBeginDate < moment() && question.topEndDate > moment()) {
                                        if (topIndex == -1)  topIndex = index;
                                        else if (question.topEndDate > questions[topIndex].topEndDate) {
                                            topIndex = index;
                                        }
                                    }
                                    //0采纳 1未采纳
                                    if (repliesStatus == 1) {
                                        if (!question._doc['adoptedReply'])  data.push(question);
                                    } else {
                                        data.push(question);
                                    }

                                    if (topIndex != -1) data[topIndex]._doc.isTop = true;


                                    callbackInner(err);
                                }
                            }, function (err) {
                                callback(err, data);
                            });
                            callbackInner(null,'执行完毕');
                        });
                }],function(err,result) {
                    logger.debug(result);
                });
            }
            //ugcIndex过时的API：针对该表操作已经废弃,ugcIndex不再推荐使用，查询慢，所有帖子查询均在question表中查询与操作
            //ugcIndex.find(opt).limit(listPageSize).sort(sort).exec(function (err, result) {
            //    if (result != null) {
            //         questionService.getQuestionListByUgcIndex(result, callback)
            //    } else {
            //        callback(null, []);
            //    }
            //});
        }
    })
};

/**
 * 根据标签获取列表
 * @param page
 * @param tagId
 * @param token
 * @param callback
 */
exports.getQuestionListByTagService = function (ts, tagId, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {

            var date = ts == '0' ? new Date() : new Date(Number(ts));

            ugcIndex.find({
                community: user.community._id,
                tag: tagId,
                lastReply: {$lt: date}
            }, '-displayOrder').limit(listPageSize).sort({
                lastReply: -1
            }).exec(function (err, result) {
                if (result != null) {
                    questionService.getQuestionListByUgcIndex(result, callback)
                } else {
                    callback(null, []);
                }
            });
        }
    })
};

/**
 * 根据索引获取问题或者其他
 * @param result
 * @param callback
 */
// 2015-10-20
exports.getQuestionListByUgcIndex = function (result, callback) {


    var topIndex = -1;
    var index = -1;

    var data = [];
    async.eachSeries(result, function (ugc, callbackInner) {
            index++;
            Question.findOne({_id: ugc.ugcId,isValid:true}, '_id desc topBeginDate topEndDate  browserCount replies.replyStatus replies._id level replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy category tag images replies dateCreated createdBy praiseCount')
                .populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                .populate('community', '_id communityName')
                .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
                .exec(function (err, question) {
                    if (question != null && question.createdBy != null) {
                        //计算问题回复数量
                        if (question.replies != null) {
                            question._doc['numberOfReplies'] = question.replies.length;
                            question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);
                            question.replies.forEach(function (reply) {
                                if (reply.replyStatus == '已采纳') {
                                    question._doc['adoptedReply'] = reply;
                                }
                            })
                        }
                        logger.debug("is doing");
                        question._doc['isPrime'] = question.level == 1;
                        question._doc['browserCountStr'] = toolUtil.transformNumber(question._doc.browserCount);
                        question._doc.replies = undefined;

                        if (question.createdBy.showUnit != null && !question.createdBy.showUnit) {
                            question.createdBy.roomUnit = undefined;
                        }
                        question.createdBy.showUnit = undefined;
                        //question._doc['isTop'] = ugc.displayOrder ? true : false;

                        if (question.topBeginDate && question.topEndDate && question.topBeginDate < moment() && question.topEndDate > moment()) {
                            if (topIndex == -1)  topIndex = index;
                            else if (question.topEndDate > result[topIndex].topEndDate) {
                                topIndex = index;
                            }
                        }

                        //question._doc['dateLastModified'] = ugc.lastReply;

                        if (question._doc.adoptedReply != null && question._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                            replyAt.findOne({replyId: question._doc.adoptedReply._id + ''}, function (err, at) {
                                if (at != null && at.uList != null) {
                                    at.uList.forEach(function (temp, i) {
                                        question._doc.adoptedReply.replyDesc = question._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                    });
                                }
                                data.push(question);
                                callbackInner()
                            }).populate('uList', '_id nickName');
                        } else {
                            data.push(question);
                            callbackInner(err);
                        }
                    } else {
                        callbackInner(err);
                    }
                });


        if (topIndex != -1) data[topIndex]._doc.isTop = true;


    }, function (err) {
        callback(err, data);
    })
};


/**
 * 获取小区所有投票
 */
exports.getAllCommunityPollListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var index = Number(page) * listPageSize;

            Question.find({
                'category': 'poll',
                'community': user.community._id,
                'isValid': true
            }, '_id desc displayOrder community category tag status images pollOptions dateCreated pollUserList createdBy').skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-displayOrder').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {

                            //如果是投票，判断用户是否已投过票，voted字段表示
                            var pollList = question.pollUserList;
                            if (pollList != null && pollList.indexOf(user._id) != -1) {
                                question._doc['voted'] = 'Yes'
                            } else {
                                question._doc['voted'] = 'No'
                            }
                            if (pollList != null) {
                                question._doc['numberOfReplies'] = pollList.length;
                            }
                            question._doc.pollUserList = undefined;

                            //过滤tag为null的问题
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }

                        });
                        callback(null, results);
                    }
                })
        }
    })
};

/**
 * 获取小区专题列表
 */
exports.getAllCommunitySpecialTopicListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var communityId = user.community._id;
            var index = Number(page) * listPageSize;

            Question.find({
                'category': 'specialTopic',
                'community': communityId,
                'isValid': true
            }, '_id title desc community browserCount replies category images dateCreated').skip(index).limit(listPageSize)
                .populate('community', '_id communityName').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {
                            question._doc['numberOfReplies'] = question.replies.length;
                            question._doc.replies = undefined;

                            question._doc.pollUserList = undefined;
                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }
                        });
                        callback(null, results);
                    }
                })
        }
    });
};


/**
 * 根据分类获取问题和投票列表
 */
exports.getCategorizedQuestionAndPollListService = function (page, tagId, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var communityId = user.community._id;
            var index = Number(page) * listPageSize;
            var date = new Date();

            Dic.findOne({_id: tagId}, 'value', function (err, tagName) {
                if (tagName.value == '推荐') {
                    questionService.getRecommendedQuestionAndPollListService(token, Number(page), callback);
                } else {
                    Question.find({
                        'tag': tagId,
                        'community': communityId,
                        'isValid': true
                    }, '_id desc community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy praiseCount').skip(index).limit(listPageSize)
                        .populate('tag', 'category value _id')
                        .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                        .populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus').sort('-dateCreated').exec(function (err, results) {
                            if (results == undefined || results == null) {
                                var msg = {
                                    "message": 'get err'
                                };
                                callback(msg, null);
                            } else {
                                results.forEach(function (question) {
                                    //计算问题回复数量
                                    if (question.replies != null) {
                                        question._doc['numberOfReplies'] = question.replies.length;
                                        question.replies.forEach(function (reply) {
                                            if (reply.replyStatus == '已采纳') {
                                                question._doc['adoptedReply'] = reply;
                                            }
                                        })
                                    }
                                    question._doc.replies = undefined;
                                    if (question._doc.tag == null || question._doc.tag.length == 0) {
                                        question._doc.tag = undefined;
                                    }
                                    question._doc.pollUserList = undefined;

                                    if (question.browserCount == null) {
                                        question.browserCount = 0;
                                    }

                                    if (question.dateLastModified > date) {
                                        question.dateLastModified = question.dateCreated;
                                    }
                                });
                                callback(null, results);
                            }
                        })
                }
            })
        }
    });
};
/**
 * 搜索问题和投票列表
 */
exports.searchQuestionAndPollListService = function (keyword, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {

            var searchArray = [];

            var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）&mdash;—|{}【】‘；：”“'。，、？]");
            var rs = "";
            for (var i = 0; i < keyword.length; i++) {
                rs = rs + keyword.substr(i, 1).replace(pattern, '');
            }

            var temp = encodeURIComponent(rs);

            if (temp == null || temp == '') {
                var res = [];
                callback(null, res);
            } else {
                console.log('temp ==' + temp);
                restClient.get('http://' + SolrHost + '/core0/select?q=%7B!edismax+mm%3D"1<50%25+4<-45%25"%7Ddesc%3A' + temp + '&fq=community%3A' + user.community._id + '&rows=20&wt=json&indent=true&hl=true&hl.fl=desc&hl.simple.pre=<font+color%3D%27%23' + hlColor + '%27>&hl.simple.post=<%2Ffont>', function (data, response) {
                    if (response.statusCode == 200) {
                        var v = false;
                        if (typeof data == 'string') {
                            try {
                                data = JSON.parse(data);
                            } catch (e) {

                            }
                        }
                        if (typeof data == "object" && data.response != null) {
                            var docs = data.response.docs;
                            var ids = new Array(docs.length);

                            for (var i = 0; i < docs.length; i++) {
                                ids[i] = docs[i]._id;
                            }

                            var questions = [];

                            async.eachSeries(ids, function (id, callbackInner) {
                                Question.findOne({
                                    _id: id, 'community': user.community._id,
                                    'isValid': true
                                }, '_id desc community browserCount category status tag images replies pollOptions dateCreated createdBy').populate('tag', 'category value _id')
                                    .populate('community', '_id communityName').populate('createdBy', '_id nickName').exec(function (err, result) {
                                        if (result != null) {
                                            questions.push(result);
                                        }
                                        callbackInner();
                                    });
                            }, function (err) {
                                questions.forEach(function (question) {
                                    question._doc.desc = data.highlighting[question._id].desc[0];

                                    //计算问题回复数量
                                    if (question.replies != null) {
                                        question._doc['numberOfReplies'] = question.replies.length;

                                        question.replies.forEach(function (reply) {
                                            if (reply.replyStatus == '已采纳') {
                                                question._doc['adoptedReply'] = reply;
                                            }
                                        })
                                    }
                                    question._doc.replies = undefined;
                                    if (question._doc.tag == null || question._doc.tag.length == 0) {
                                        question._doc.tag = undefined;
                                    }
                                    if (question.browserCount == null) {
                                        question.browserCount = 0;
                                    }
                                    if (question.browserCount >= 200) {
                                        question._doc['hot'] = true;
                                    } else {
                                        question._doc['hot'] = false;
                                    }
                                });
                                callback(null, questions);
                            });
                        } else {
                            logger.error(data);
                            callback(null, searchArray);
                        }
                    } else {
                        callback(null, searchArray);
                    }
                }).on('error', function (err) {
                    logger.error('search went wrong on the request' + err.message);
                    callback(null, searchArray);
                });
            }
        }
    });
};

/**
 * 获取专家解答问题
 */
exports.getExpertRepliedQuestionListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {

            var index = Number(page) * listPageSize;
            //假数据
            Question.find({
                'community': user.community._id,
                'isValid': true,
                'replies': {'$not': {'$size': 0}},
                'replies.replyType': {'$ne': null}
            }, 'desc createdBy browserCount replies.replyDesc replies.dateReplied replies.repliedBy replies.replyType').skip(index).limit(listPageSize).populate('createdBy', '_id nickName images').populate('replies.repliedBy', '_id nickName images')
                .exec(function (err, results) {
                    if (results != null) {
                        results.forEach(function (result) {

                            //去掉非专家回复，显示最新专家回复
                            var replies = result.replies;
                            if (replies != null && replies.length != 0) {

                                replies.sort(function (a, b) {
                                    return b.dateReplied - a.dateReplied;
                                });

                                for (var i = 0; i < replies.length; i++) {
                                    if (replies[i].replyType != null) {
                                        replies.splice(0, i);
                                        break;
                                    }
                                }
                                result.replies = [replies[0]];
                            }

                            if (result.browserCount == null) {
                                result.browserCount = 0;
                            }
                            if (result.browserCount >= 200) {
                                result._doc['hot'] = true;
                            } else {
                                result._doc['hot'] = false;
                            }
                        });
                        callback(null, results);
                    } else {
                        callback(null, null);
                    }
                });
        }
    });
};

/**
 * 最新问题和投票
 */
exports.getLatestQuestionListService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var index = Number(page) * listPageSize;

            Question.find({
                'community': user.community._id,
                'isValid': true
            }, '_id desc displayOrder browserCount community category status tag images replies pollOptions pollUserList dateCreated createdBy').skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images').sort('-displayOrder').sort('-dateCreated').exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var msg = {
                            "message": 'get err'
                        };
                        callback(msg, null);
                    } else {
                        results.forEach(function (question) {

                            //如果是投票，判断用户是否已投过票，voted字段表示
                            if (question.category == 'poll') {
                                var pollList = question.pollUserList;
                                if (pollList != null && pollList.indexOf(user._id) != -1) {
                                    question._doc['voted'] = 'Yes'
                                } else {
                                    question._doc['voted'] = 'No'
                                }
                                if (pollList != null) {
                                    question._doc['numberOfReplies'] = pollList.length;
                                }
                            } else {
                                //计算问题回复数量
                                if (question.replies != null) {
                                    question._doc['numberOfReplies'] = question.replies.length;

                                    question.replies.forEach(function (reply) {
                                        if (reply.replyStatus == '已采纳') {
                                            question._doc['adoptedReply'] = reply;
                                        }
                                    })
                                }
                            }
                            //过滤tag为null的问题
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }
                            question._doc.replies = undefined;
                            question._doc.pollUserList = undefined;

                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }
                            if (question.browserCount >= 200) {
                                question._doc['hot'] = true;
                            } else {
                                question._doc['hot'] = false;
                            }

                        });
                        callback(null, results);
                    }
                })
        }
    })
};


/**
 * 获取达人排行榜
 */
exports.getTalentListService = function (tagId, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var data = [];
            Users.findOne({nickName: '小6客服'}, '_id', function (err, result) {
                QuestionReplyStatistics.find({
                    'tag': tagId,
                    'community': user.community._id,
                    'user': {$ne: result._id}
                }, 'user replyCount adoptedCount').populate('user', '_id nickName images userType authenticationStatus community').exec(function (err, results) {
                    if (results != null) {

                        results.forEach(function (qu) {
                            if (qu.user != null && qu.user.community != null && qu.user.community == user.community._id) {
                                data.push(qu);
                            }
                        });

                        data.sort(function (a, b) {
                            if (a.user.userType != 'talent' && b.user.userType == 'talent') {
                                return 1
                            } else if (a.user.userType == 'talent' && b.user.userType != 'talent') {
                                return -1
                            } else if (a.user.authenticationStatus && !b.user.authenticationStatus) {
                                return -1
                            } else if (!a.user.authenticationStatus && b.user.authenticationStatus) {
                                return 1
                            } else {
                                return (b.replyCount + b.adoptedCount) - (a.replyCount + a.adoptedCount);
                            }

                        });
                    }
                    callback(err, data);
                })
            });

        }
    });
};


//==============================新版求助==================================


exports.getCategoryQuestionListService = function (token, category, page, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var communityId = user.community._id;
            var index = Number(page) * listPageSize;

            var date = new Date();

            Question.find({
                'category': category,
                'community': communityId,
                'isValid': true
            }, '_id desc categoryOrder community replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy praiseCount').skip(index).limit(listPageSize).populate('tag', 'category value _id')
                .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                .populate('community', '_id communityName').populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit').sort({
                    categoryOrder: -1,
                    dateLastModified: -1
                }).exec(function (err, results) {
                    if (results == undefined || results == null) {
                        var data = [];
                        callback(null, data);
                    } else {
                        results.forEach(function (question) {
                            //计算问题回复数量
                            if (question.replies != null) {
                                question._doc['numberOfReplies'] = question.replies.length;

                                question.replies.forEach(function (reply) {
                                    if (reply.replyStatus == '已采纳') {
                                        question._doc['adoptedReply'] = reply;
                                    }
                                })
                            }
                            question._doc.replies = undefined;
                            if (question._doc.tag == null || question._doc.tag.length == 0) {
                                question._doc.tag = undefined;
                            }

                            if (question.browserCount == null) {
                                question.browserCount = 0;
                            }
                            //置顶标识
                            question._doc['isTop'] = question._doc.categoryOrder ? true : false;
                            question._doc.categoryOrder = undefined;

                            if (question.dateLastModified > date) {
                                question.dateLastModified = question.dateCreated;
                            }

                            if (question.createdBy.showUnit != null && !question.createdBy.showUnit) {
                                question.createdBy.roomUnit = undefined;
                            }
                            question.createdBy.showUnit = undefined;
                        });
                        callback(null, results);
                    }
                })
        }
    });
};
/*  宝宝树66小区二次改造    add   gct  20170807   start   */
exports.getCommunityByUserID=function(token,callback)
{
    async.series([
        function (callbackInner) {
            Users.find({_id: token},function (err,result) {
                /*
                 }).exec(function()
                 {*/

                var communityArray=[];
                for(var i=0;i<result.length;i++)
                {
                    communityArray.push(result[i].community);
                }
                Community.find({_id:{$in:communityArray}},callbackInner);
                /*$(result).each(function(index,element)
                 {
                 communityArray.push(element.community);
                 });*/
            });

        }
    ],
        function (err,result) {
            var resultArray=[];
            for(var i=0;i<result[0].length;i++)
            {
                var resultModel=result[0][i];
                resultArray.push(resultModel);
                console.log(resultModel);
            }
            callback(err,resultArray);
        })
}
/*  宝宝树66小区二次改造    add   gct  20170807   end   */
/*  宝宝树66小区二次改造    add   gct  20170804   start   */
exports.getCommunityAllService=function(token,callback)
{
    async.series([
        function (callbackInner) {
            AmbassadorCommunity.find({user: token,isValid:true},function (err,result) {
            /*
            }).exec(function()
            {*/

                var communityArray=[];
                for(var i=0;i<result.length;i++)
                {
                    communityArray.push(result[i].community);
                }
                Community.find({_id:{$in:communityArray},isValid:true},callbackInner);
               /*$(result).each(function(index,element)
               {
                  communityArray.push(element.community);
               });*/
            });

        },

    ],
       function (err,result) {
            var resultArray=[];
            for(var i=0;i<result[0].length;i++)
            {
                var resultModel=result[0][i];
                resultArray.push(resultModel);
                console.log(resultModel);
            }
           callback(err,resultArray);
       })


}
/*  宝宝树66小区二次改造    add   gct  20170804   end   */

exports.getCategoryQuestionListNewService = function (req, token, category, ts,flag,communityId, callback) {
    var communityId=communityId;
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);

        } else {
            /*  宝宝树66小区二次改造    add   gct  20170808   start   */

            if("0"==flag)
            {
                 communityId = user.community._id;
            }
            /*else
            {
                     communityId =communityId;
            }*/
            /*  宝宝树66小区二次改造    add   gct  20170808   end   */
            var date = ts == '0' ? new Date() : new Date(Number(ts));

            var opt = {
                category: category,
                community: communityId,
                isValid: true
            };

            opt['dateCreated'] = {$lt: date}; // 当无此条件时，会出现数据重复的情况
            var sort = {};

            if (ts != '0') { opt.categoryOrder = null;}
            else { sort.categoryOrder = -1;}


            if (req.cparams && req.cparams.level == 1 && req.cparams.reported == 0) {
                opt.level = 1;
            }

            if (req.cparams && req.cparams.noreply == 1 && req.cparams.reported == 0) {
                opt['$or'] = [{replies:{$exists: false}},{replies:{$size: 0}}];
            }


            if (req.cparams && req.cparams.noreply_t == 1 && req.cparams.reported == 0) {
                var time = new Date(new Date().getTime() - 10 * 60 * 1000);
                opt['$or'] = [{replies:{$exists: false}},{replies:{$size: 0}}];
                opt.dateCreated = {$lt: time};
            }

            sort['dateCreated'] = -1;


            var topIndex = -1;
            var index = 0;

            var data = [];

            /****
             * 被举报的帖子列表
             * @type {boolean} 判断是否筛选出举报帖子，忽视其他条件
             */
            var isReported = false;
            if (req.cparams && req.cparams.reported == 1) {
                isReported = true;
            }

            if(isReported) {
                <!--  宝宝树66小区三次改造    mod   guo.xiaomin  20171016  start   -->
                // questionService.getReportedQuestionList(opt['dateCreated'],sort,callback); // 旧
                questionService.getReportedQuestionList(opt['dateCreated'],sort,communityId,callback); // 新
                <!--  宝宝树66小区三次改造    mod   guo.xiaomin  20171016  end   -->
            }
            else {
                async.waterfall([function(callbackInner) {
                    Community.findOne({_id:opt.community},'communityType').exec(function(err,result)
                    {
                        logger.debug(result);
                        if(result.communityType == 0){
                            delete  opt.community;
                        }
                        callbackInner(null,opt);
                    });
                },function(argv,callbackInner){
                Question.find(argv, '_id desc categoryOrder community replies.replyStatus replies._id replies.replyDesc level replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status images replies dateCreated dateLastModified createdBy praiseCount')
                    .limit(listPageSize)
                    .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                    .populate('community', '_id communityName')
                    .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
                    .sort(sort).exec(function (err, results) {
                    if (results == undefined || results == null) {
                        callback(null, data);
                    } else {

                        async.eachSeries(results, function (question, c1) {
                            if (question.createdBy != null) {
                                if (question.replies != null) {
                                    question._doc['numberOfReplies'] = question.replies.length;
                                    question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);

                                    question.replies.forEach(function (reply) {
                                        if (reply.replyStatus == '已采纳') {
                                            question._doc['adoptedReply'] = reply;
                                        }
                                    })
                                }
                                question._doc['isPrime'] = question.level == 1;
                                question._doc['browserCountStr'] = toolUtil.transformNumber(question._doc.browserCount);
                                question._doc.replies = undefined;
                                if (question._doc.tag == null || question._doc.tag.length == 0) {
                                    question._doc.tag = undefined;
                                }

                                if (!question.browserCount) question.browserCount = 0;

                                //置顶标识
                                //question._doc['isTop'] = question._doc.categoryOrder ? true : false;


                                if (question.topBeginDate && question.topEndDate && question.topBeginDate < moment() && question.topEndDate > moment()) {
                                    if (topIndex == -1)  topIndex = index;
                                    else if (question.topEndDate > result[topIndex].topEndDate) {
                                        topIndex = index;
                                    }
                                }

                                if (question.createdBy.showUnit != null && !question.createdBy.showUnit) {
                                    question.createdBy.roomUnit = undefined;
                                }
                                question.createdBy.showUnit = undefined;


                                if (question._doc.adoptedReply != null && question._doc.adoptedReply.replyDesc.indexOf(atFlag) != -1) {
                                    replyAt.findOne({replyId: question._doc.adoptedReply._id + ''}, function (err, at) {
                                        if (at != null && at.uList != null) {
                                            at.uList.forEach(function (temp, i) {
                                                question._doc.adoptedReply.replyDesc = question._doc.adoptedReply.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                            });
                                        }

                                        //0采纳 1未采纳
                                        if (req.cparams && req.cparams.noadopt == 1) {
                                            if (!question._doc['adoptedReply'])  data.push(question);
                                        }else {
                                            data.push(question);
                                        }
                                        c1();
                                    }).populate('uList', '_id nickName');
                                } else {

                                    if (req.cparams && req.cparams.noadopt == 1) {
                                        if (!question._doc['adoptedReply'])  data.push(question);
                                    }else {
                                        data.push(question);
                                    }
                                    c1();
                                }
                            } else {
                                c1();
                            }

                            index++;
                            if (topIndex != -1) data[topIndex]._doc.isTop = true;


                        }, function (err, result) {
                            callback(null, data);
                            callbackInner(null,"执行完毕");
                        });
                    }
                })}],function(err,result) {
                    logger.debug(result);
                });
            }
        }
    });
};

/***
 * 未处理 举报的帖子 列表
 * @param ts 以日期为分页标记
 * @param callback
 */
<!--  宝宝树66小区三次改造    mod   guo.xiaomin  20171016  start   -->
// exports.getReportedQuestionList = function(ts,sort,callback) // 旧
exports.getReportedQuestionList = function(ts,sort,communityId,callback) // 新
{
    // QuestionReport.find({reportStatus :0,dateCreated:ts},'question')
    QuestionReport.find({reportStatus :0,dateCreated:ts,questionCommunity:communityId},'question')
        .limit(listPageSize).sort(sort).exec(function(err,results) {
            if(results) {
                async.mapSeries(results,function(question,callback) {
                    questionService.getFormattedQuestionWithModerator(question.question,callback)
                },function(err,question) {
                    callback(null,question);
                });
            } else {
                callback(null,null);
            }
    });
    <!--  宝宝树66小区三次改造    mod   guo.xiaomin  20171016  end   -->
};

/***
 * 同步 question_reports 数据
 * reportStatus : {type: Number, default: 0}//-1:已忽略 0：未处理 1：已删除
 */
exports.updateQuestionReports = function(questionId,reportStatus,callback)
{
    if(!reportStatus)
    {
        throw  new Error("需要更新的状态:Null,出错");
    }

    QuestionReport.update({question:questionId},{reportStatus:reportStatus},function(error)
    {
        callback(error);
    });
};

/**
 * 版主管理-对每个Question 对数据预处理
 * 根据索引获取问题
 * @param result
 * @param callback
 * @date 2016-1-25
 */
exports.getFormattedQuestionWithModerator = function (questionId, callback) {

    Question.findOne({_id: questionId,isValid:true}, '_id desc topBeginDate topEndDate  browserCount replies.replyStatus replies._id level replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy category tag images replies dateCreated createdBy praiseCount')
        .populate('tag', 'category value _id')
        .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
        .populate('community', '_id communityName')
        .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
        .exec(function (err, question) {
            if (question != null && question.createdBy != null) {
                //计算问题回复数量
                if (question.replies != null) {
                    question._doc['numberOfReplies'] = question.replies.length;
                    question._doc['replyCountStr'] = toolUtil.transformNumber(question.replies.length);
                    question.replies.forEach(function (reply) {
                        if (reply.replyStatus == '已采纳') {
                            question._doc['adoptedReply'] = reply;
                        }
                    })
                }
                question._doc['isPrime'] = question.level == 1;
                question._doc['browserCountStr'] = toolUtil.transformNumber(question._doc.browserCount);
                question._doc.replies = undefined;

                if (question.createdBy.showUnit != null && !question.createdBy.showUnit) {
                    question.createdBy.roomUnit = undefined;
                }
                question.createdBy.showUnit = undefined;
                if(question){
                    callback(null,question);
                }
            } else {
                callback(err,null);
            }
        });

};


//=========================================== web端=============================================

/**
 * questionService.js
 * 创建问题
 * author:chenjinzhuan
 */
exports.createQuestionService = function (input, callback) {
    var temp = new Question();
    temp.category = input.category;
    temp.desc = input.desc;
    temp.status = '未解决';
    temp.createdBy = input._id;
    temp.community = input.community;

    if (data == 'unknown') {
        temp.save(function (err, question) {
            callbackInner(null, question);
        })
    } else {
        Dic.findOne({'value': data}, '', function (err, result) {
            if (result == null) {
                temp.save(function (err, question) {
                    callbackInner(null, question);
                });
            } else {
                temp.tag = result._id;
                temp.save(function (err, question) {
                    callback(null, question);
                });
            }
        })
    }


};

/**
 * questionService.js
 * 更新问题
 * author:chenjinzhuan
 */
exports.updateOneQuestionService = function (id, input, callback) {

    async.series([
        //function (callbackInner) {
        //    Question.findOne({'_id': id}, function (err, result) {
        //        var replyC = 0;
        //        if (result.replies != null) {
        //            replyC = result.replies.length;
        //        }
        //
        //        var tags = result.tag;
        //
        //        Dic.find({'_id': {'$in': tags}, 'category': '02'}, '_id', function (err, res) {
        //            if (res != null) {
        //                res.forEach(function (tag) {
        //                    QuestionAndReplyCount.findOne({
        //                        'community': result.community,
        //                        'tag': tag._id
        //                    }, '', function (err, qc) {
        //                        if (qc == null) {
        //                            var temp = new QuestionAndReplyCount();
        //                            temp.questionCount = 0;
        //                            temp.replyCount = 0;
        //                            temp.community = result.community;
        //                            temp.tag = tag;
        //                            temp.save();
        //                        } else {
        //                            qc.questionCount -= 1;
        //                            qc.replyCount -= replyC;
        //                            qc.save();
        //                        }
        //                    })
        //                })
        //            }
        //            callbackInner(err, null);
        //        })
        //    })
        //},
        //function (callbackInner) {
        //    var tags = input.tag;
        //
        //    Question.findOne({'_id': id}, function (err, result) {
        //        var replyC = 0;
        //        if (result.replies != null) {
        //            replyC = result.replies.length;
        //        }
        //
        //        Dic.find({'_id': {'$in': tags}, 'category': '02'}, '_id', function (err, res) {
        //            res.forEach(function (tag) {
        //                QuestionAndReplyCount.findOne({
        //                    'community': result.community,
        //                    'tag': tag
        //                }, '', function (err, qc) {
        //                    if (qc == null) {
        //                        var temp = new QuestionAndReplyCount();
        //                        temp.questionCount = 1;
        //                        temp.replyCount = replyC;
        //                        temp.community = result.community;
        //                        temp.tag = tag;
        //                        temp.save();
        //                    } else {
        //                        qc.questionCount += 1;
        //                        qc.replyCount += replyC;
        //                        qc.save();
        //                    }
        //                })
        //            });
        //            callbackInner(err, null);
        //        })
        //    });
        //},
        function (callbackInner) {
            Question.update({_id: id},
                {
                    $set: {
                        'desc': input.desc,
                        'tag': input.tag
                    }
                }, callbackInner);
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: id}, {$set: {'tag': input.tag}}, callbackInner);
        }
    ], callback);
};

/**
 * questionService.js
 * 更新问题
 * author:chenjinzhuan
 */
exports.backOfficeUpdateQuestionByModerator = function (id, input, callback) {

    var tags = input.tag.split(",");

    async.series([
        function (callbackInner) {
            Question.update({_id: id},
                {
                    $set: {
                        'desc': input.desc,
                        'tag': tags
                    }
                }, callbackInner);
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: id}, {$set: {'tag': tags}}, callbackInner);
        }
    ], callback);
};

/**
 * questionService.js
 * 获取问题列表
 * author:chenjinzhuan
 */
exports.getQuestionListService = function (callback) {
    Question.find({
        category: 'question',
        isValid: true
    }).populate('community', '_id communityName communityAddress')
        .populate('tag', 'value')
        .populate('createdBy', 'userName email mobilePhone nickName').sort('-dateCreated').exec(function (err, results) {
            if (err) {
                return callback(err);
            } else {
                if (results != null) {
                    results.forEach(function (question) {
                        var data = [];
                        if (question.tag != null) {
                            question.tag.forEach(function (t) {
                                data.push(t.value);
                            });
                            question._doc.tag = data
                        }
                    })
                }
                return callback(null, results);
            }
        });
};

/**
 * questionService.js
 * 根据条件问题列表
 * author:chenjinzhuan
 */
exports.searchQuestionService = function (question, callback) {
    //根据关键词查询问题
    Question.find({desc: new RegExp(question.key)}).populate('community', '_id communityName communityAddress')
        .populate('createdBy', 'userName email mobilePhone nickName').exec(function (err, results) {
            if (err) {
                return callback(err);
            } else if (results == undefined || results == null) {
                return callback('no results', null);
            } else {
                //logger.debug('results:'+ results);
                return callback(null, results);
            }
        });

    //async.waterfall([
    //    //查询小区的id
    //    function(callbackInner){
    //        Community.findOne({'communityName':question.communityName},'_id', function (err, results) {
    //            if(err){
    //                return callback(err);
    //            }else if(results == undefined || results == null){
    //                return callback('no results',null);
    //            }else{
    //                return callbackInner(null, results);
    //            }
    //        });
    //    },
    //    //根据小区id查询问题
    //    function(results){
    //        Question.find({'community':results._id}).populate('community', '_id communityName communityAddress')
    //            .populate('createdBy','userName email mobilePhone nickName').exec(function(err,results){
    //                if(err){
    //                    return callback(err);
    //                }else if(results == undefined || results == null){
    //                    return callback('no results', null);
    //                }else{
    //                    //logger.debug('results:'+ results);
    //                    return callback(null,results);
    //                }
    //            });
    //    }
    //]);

};

/**
 * questionService.js
 * 通过Id获取问题
 * author:chenjinzhuan
 */
exports.getQuestionByIdService = function (id, callback) {

    Question.findOne({_id: id}).populate('community', '_id communityName communityAddress').populate('tag', 'value')
        .populate('createdBy', 'userName email mobilePhone nickName').exec(function (err, results) {
            if (err) {
                return callback(err);
            } else if (results == undefined || results == null) {
                return callback('no results', null);
            } else {

                for (var i = 0; i < results["images"].length; i++) {
                    results["images"][i] = fastDfsHostIp + results["images"][i]["imageURL"];
                }
                logger.debug(results["images"]);

                return callback(null, results);
            }
        });
};

/**
 * questionService.js
 * 删除问题
 * author:chenjinzhuan
 */
exports.deleteOneQuestionService = function (id, callback) {
    Question.findOneAndRemove({_id: id}, callback);
};

/**
 * questionService.js
 * 修改问题顺序
 * author:chenjinzhuan
 */
exports.changeQuestionOrderService = function (question, callback) {
    if (question.order >= 1 && question.order <= 5) {
        var displayOrder = 6 - question.order;
    } else {
        return callback('wrong order');
    }

    //1.查找问题所属小区的所有问题
    async.waterfall([
        function (callbackInner) {
            Question.find({community: question.community._id}, function (err, results) {
                if (err) {
                    return callback(err);
                } else if (results == undefined || results == null) {
                    return callback('no results', null);
                } else {
                    //logger.debug('results:'+ results);
                    return callbackInner(null, results);
                }
            });
        },
        //2.判断所有问题中是否存在给定的顺序，如果存在，则将问题的displayorder置空
        function (results, callbackInner) {
            for (var i = 0; i < results.length; ++i) {
                if (results[i].displayOrder == displayOrder) {
                    Question.update({_id: results[i]._id}, {$set: {displayOrder: null}}, function (err, results) {
                        if (err) {
                            return callbackInner(err);
                        } else if (results == undefined || results == null) {
                            return callbackInner('no results');
                        } else {
                            //logger.debug('results:'+ results);
                            return callbackInner(null);
                        }
                    });
                    //return callbackInner(null);
                }
            }
            //如果不存在已有的displayOrder，则直接返回
            return callbackInner(null);
        },
        //3.设置displayOrder
        function (callbackInner) {
            Question.findOneAndUpdate({'_id': question._id}, {'displayOrder': displayOrder}, function (err, results) {
                if (err) {
                    return callbackInner(err);
                } else if (results == undefined || results == null) {
                    return callbackInner('no results', null);
                } else {
                    //logger.debug('results:'+ results);
                    return callback(null, results);
                }
            });
        }
    ], callback);
};

/**
 * questionService.js
 * 获取问题列表
 * author:chenjinzhuan
 */
exports.getReplyListService = function (questionId, callback) {
    Question.find({_id: questionId}).populate('community', '_id communityName communityAddress')
        .populate('createdBy', 'userName email mobilePhone nickName')
        .populate('replies.repliedBy', 'userName email mobilePhone nickName')
        .exec(function (err, results) {
            if (err) {
                return callback(err);
            } else if (results == undefined || results == null || results.length == 0) {
                return callback('no results', null);
            } else {
                return callback(null, results[0]);
            }
        });
};

/**
 * questionService.js
 * 根据条件问题列表
 * author:chenjinzhuan
 */
exports.searchReplyService = function (input, callback) {
    async.waterfall([
            //根据问题Id查询所有回复
            function (callbackInner) {
                //根据关键词查询问题
                Question.find({'_id': input.questionId}).populate('community', '_id communityName communityAddress')
                    .populate('createdBy', 'userName email mobilePhone nickName')
                    .populate('replies.repliedBy', 'userName email mobilePhone nickName')
                    .exec(function (err, results) {
                        if (err) {
                            return callback(err);
                        } else if (results == undefined || results == null || results.length == 0) {
                            return callback('no results', null);
                        } else {
                            //logger.debug('results:'+ results);
                            return callbackInner(null, results[0].replies);
                        }
                    });
            },
            //查找回复数组中匹配的回复放入另一个数组中返回
            function (replies) {
                var reg = new RegExp(input.key);
                var results = [];
                for (var i = 0; i < replies.length; ++i) {
                    if (replies[i].replyDesc.match(reg)) {
                        results.push(replies[i]);
                    }
                }
                return callback(null, results);
            }
        ]
    );
};

exports.getNoReplyQuestionListService = function (communityId, callback) {

    var time = new Date(new Date().getTime() - 10 * 60 * 1000);

    //var opt = {
    //    replies: {$size: 0},
    //    isValid: true,
    //    dateCreated: {$lt: time}
    //};
    //
    //if (communityId != 1) {
    //    opt.community = communityId;
    //}

    if (communityId == '1') {
        Question.find({
            replies: {$size: 0},
            isValid: true,
            dateCreated: {$lt: time}
        }, '_id desc createdBy community dateCreated').populate('community', '_id communityName').populate('createdBy', '_id nickName').sort('dateCreated').exec(callback)
    } else {
        Question.find({
            replies: {$size: 0},
            community: communityId,
            isValid: true,
            dateCreated: {$lt: time}
        }, '_id desc createdBy community dateCreated').populate('community', '_id communityName').populate('createdBy', '_id nickName').sort('dateCreated').exec(callback)
    }
};


exports.backOfficePostReplyService = function (questionId, input, callback) {
    Users.findOne({nickName: '小6客服'}, '_id', function (err, result) {
        questionService.postReplyService(result._id, questionId, input, callback)
    })
};

exports.getReportQuestionService = function (communityId, callback) {

    var data = [];

    QuestionReport.distinct("question", function (err, results) {
        async.each(results, function (questionId, callback) {
            if (communityId == '1') {
                Question.findOne({
                    _id: questionId
                }, 'desc community replies createdBy dateCreated').populate('createdBy', '_id nickName').populate('community', '_id communityName').exec(function (err, result) {
                    QuestionReport.count({question: questionId}, function (err, count) {
                        if (result != null) {
                            result._doc['count'] = count;
                            data.push(result);
                        }
                        callback();
                    })

                })
            } else {
                Question.findOne({
                    community: communityId,
                    _id: questionId
                }, 'desc community replies dateCreated').populate('community', '_id communityName').exec(function (err, result) {
                    QuestionReport.count({question: questionId}, function (err, count) {
                        if (result != null) {
                            result._doc['count'] = count;
                            data.push(result);
                        }
                        callback();
                    })
                })
            }
        }, function (err) {
            if (err) {
                var msg = {
                    "message": "get err"
                };
                callback(msg, null);
            } else {
                data.sort(function (a, b) {
                    return b.dateCreated - a.dateCreated;
                });
                callback(null, data);
            }
        })
    });
};

/**
 * 删除举报问题
 * @param questionId
 * @param callback
 */
exports.deleteReportQuestionService = function (questionId, callback) {
    async.series([
        function (callbackInner) {
            questionService.deleteQuestionService(questionId, callbackInner);
        },
        function (callbackInner) {
            QuestionReport.remove({'question': questionId}, callbackInner)
        }
    ], callback)
};





// 导出问题Service
exports.exportQuestionListService = function (input, page, size, callback) {

    var option = {};

    size = Number(size);
    var index = (Number(page) - 1) * size;
    var date = new Date();





    option['isValid'] = true;
    if (input.level == 1) {
        option.level = 1;
    }else if (input.level == 0) {
        option['$or'] = [{level:{$exists: false}},{level:0}];
    }


    if (input.createdBy != null) {
        option['createdBy'] = input.createdBy;
    }

    if (input.community != null) {
        option['community'] = input.community;
    }

    if (input.category != null) {
        option['category'] = input.category;
    }

    if (input.nick != null) {
        option['nick'] = new RegExp(input.nick);
    }

    if (input.desc != null) {
        option['desc'] = new RegExp(input.desc);
    }


    //是否有回复
    if (input.repliesflg == 'no') {
        option['$or'] = [{replies:{$exists: false}},{replies:{$size: 0}}];
    } else if (input.repliesflg == 'yes') {
        option['replies'] = {$exists: true, $not: {$size: 0}};
    }

    if (input.tagflg == 'no') {
        option['$or'] = [{tag:{$exists: false}},{tag:{$size: 0}}];
    } else if (input.tagflg == 'yes') {
        option['tag'] = {$exists: true, $not: {$size: 0}};
    }

    if (option['enddate'] == null || option['enddate'] == "") {
        option['enddate'] = '9998-12-31';
    }


    if (input.startdate != null && input.startdate != "") {
        option['dateCreated'] = {"$gte": new Date(option['startdate'])};
    }

    if (input.enddate != null && input.enddate != "") {
        if (option['dateCreated'] != null && option['dateCreated'] != "") {
            option['dateCreated'] = {
                "$gte": moment(option['startdate'])._d,
                "$lte": moment(option['enddate']).add(1, 'day')._d
            };
        } else {
            option['dateCreated'] = {"$lte": moment(input.enddate).add(1, 'day')._d};
        }
    }
    option['startdate'] = null;
    option['enddate'] = null;
    logger.debug(option);
    for (var item in option) {
        if (option[item] == null) {
            delete option[item];
        }
    }

    var sortType = input.sortType == "reply" ? {
        categoryOrder:-1,
        dateLastModified: -1
    } : {
        categoryOrder:-1,
        dateCreated: -1
    };

    var sortTypeAll = input.sortType == "reply" ? {
        dateLastModified: -1
    } : {
        dateCreated: -1
    };

    delete option['sortType'];

    logger.debug(option);

    Community.find({}).exec(function (err, result) {
        var arry = {};
        async.each(result, function (item, callback) {
            arry[item.id] = item;
            callback();
        }), function (err) {

        };


        async.series([
            function (callback) {
                //logger.debug(option['nick']);
                if (option['createdBy'] == null) {

                    var useropt = {};
                    if (option['nick'] != undefined && option['nick'] != null && option['nick'] != "") {
                        useropt['nickName'] = new RegExp(option['nick']);
                    }
                    else {
                        useropt['_id'] = null;
                    }
                    Users.find(useropt, function (err, results) {
                        if (results.length > 0) {
                            var queryUserIn = {};
                            queryUserIn["$in"] = [];
                            for (var i = 0, l = results.length; i < l; i++) {
                                queryUserIn["$in"].push(results[i]['_id']);
                            }
                            option["createdBy"] = queryUserIn;
                        }
                        callback(null, null);
                    });
                } else {
                    callback(null, null);
                }
            },
            function (callback) {
                option['nick'] = null;
                //logger.debug('sdfs');
                //logger.debug(option);
                Question.count(option, function (err, count) {
                    //logger.debug(option);
                    //logger.debug(count);
                    callback(err, Math.ceil(count / size));
                });
                //callback(null,null);
            },
            function (callback) {
                if (option.category != null) {
                    logger.debug(option);

                    Question.find(option, '_id categoryOrder desc community aroundCommunity replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy recommend level')
                        .skip(index).limit(size).populate('tag', 'value').populate('replies.repliedBy', '_id community nickName images authenticationStatus')
                        .populate('community', '_id communityName').populate('aroundCommunity', '_id communityName').populate('createdBy', '_id nickName userType images authenticationStatus')
                        .sort(sortType).exec(function (err, results) {
                            //logger.debug('results');
                            //logger.debug(results.length);
                            if (err) {
                                return callback(err);
                            } else {
                                if (results != null) {
                                    results.forEach(function (question) {
                                        var data = [];
                                        if (question.tag != null) {
                                            question.tag.forEach(function (t) {
                                                data.push(t.value);
                                            });
                                            question._doc.tag = data
                                        }

                                        // 周边小区
                                        data = [];
                                        if (question.aroundCommunity != null) {
                                            question.aroundCommunity.forEach(function (t) {
                                                data.push(t.communityName);
                                            });
                                            question._doc.aroundCommunity = data;
                                        }

                                        if (question.images != null) {
                                            question.images.forEach(function (img) {
                                                img.imageURL = fastDfsHostIp + img.imageURL;
                                                logger.debug(img.imageURL);
                                            });
                                        }
                                        if (question.dateLastModified > date) {
                                            question.dateLastModified = question.dateCreated;
                                        }
                                        if (question.replies != null) {
                                            //logger.debug(question.replies);
                                            question.replies.forEach(function (repliy) {
                                                var communityName = '';
                                                if (repliy.repliedBy.nickName != '小6客服') {
                                                    communityName = arry[repliy.repliedBy.community]['communityName'];
                                                }
                                                repliy.repliedBy._doc['communityName'] = communityName;

                                            });
                                        }

                                    });

                                }
                                return callback(null, results);
                            }
                        })
                } else {
                    logger.debug(option.category);
                    //logger.debug(option);

                    Question.find(option, '_id allOrder desc community aroundCommunity replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy recommend level')
                        .skip(index).limit(size).populate('tag', 'value').populate('replies.repliedBy', '_id community nickName images authenticationStatus')
                        .populate('community', '_id communityName').populate('aroundCommunity', '_id communityName').populate('createdBy', '_id nickName userType images authenticationStatus')
                        .sort(sortTypeAll).exec(function (err, results) {
                            if (err) {
                                return callback(err);
                            } else {
                                if (results != null) {
                                    async.each(results, function(question, callback){
                                        var data = [];
                                        if (question.tag != null) {
                                            question.tag.forEach(function (t) {
                                                data.push(t.value);
                                            });
                                            question._doc.tag = data
                                        }

                                        // 周边小区
                                        data = [];
                                        if (question.aroundCommunity != null) {
                                            question.aroundCommunity.forEach(function (t) {
                                                data.push(t.communityName);
                                            });
                                            question._doc.aroundCommunity = data;
                                        }


                                        if (question.images != null) {
                                            question.images.forEach(function (img) {
                                                img.imageURL = fastDfsHostIp + img.imageURL;
                                                //logger.debug(img.imageURL);
                                            });
                                        }
                                        if (question.dateLastModified > date) {
                                            question.dateLastModified = question.dateCreated;
                                        }

                                        if (question.replies != null) {
                                            async.each(question.replies, function(repliy, callback){
                                                var communityName = '';
                                                if (repliy.repliedBy.nickName != '小6客服') {
                                                    communityName = arry[repliy.repliedBy.community]['communityName'];
                                                }
                                                repliy.repliedBy._doc['communityName'] = communityName;

                                                replyAt.findOne({replyId: repliy._id + ''}, function (err, at) {
                                                    if (at != null && at.uList != null) {
                                                        at.uList.forEach(function (temp, i) {
                                                            if(temp.nickName != undefined)repliy.replyDesc = repliy.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                        });
                                                    }
                                                    callback(null);// must call once
                                                }).populate('uList', '_id nickName');

                                            }, function(err){
                                                callback(null);// must call once
                                            });
                                        }
                                    }, function(err){
                                        callback(null, results)
                                    });
                                }

                            }
                        })
                }
            }

        ], callback);
    });

};





exports.getRecommendQuestionService = function (option, page, size, callback) {

    size = Number(size);
    var index = (Number(page) - 1) * size;
    var date = new Date();

    if (option['nick'] != null) {
        option['nick'] = new RegExp(option['nick']);
    }

    if (option['desc'] != null) {
        option['desc'] = new RegExp(option['desc']);
    }

    //if (option['userId'] != null) {
    //    option['createdBy'] = option['userId'];
    //}

    //是否有回复
    if (option['repliesflg'] == 'no') {
        option['replies'] = {$size: 0};
    } else if (option['repliesflg'] == 'yes') {
        option['replies'] = {$not: {$size: 0}};
        //option['replies'] = {$exists: true};
        //option.$where = "this.replies.length>0";
    }
    option['repliesflg'] = null;


    //opt.tag = {$exists: true};
    //opt.$where = "this.tag.length>0"
    //是否有标签
    if (option['tagflg'] == 'no') {
        option['$or'] = [{tag:{$exists: false}},{tag:{$size: 0}}];
    } else if (option['tagflg'] == 'yes') {
        option['tag'] = {$exists: true, $not: {$size: 0}};
        //option['tag'] = {$exists: true};
        //option.$where = option.$where+"this.tag.length>0";
    }
    option['tagflg'] = null;

    if (option.level == 0) {
        option.level = {$ne: 1}
    }

    if (option['enddate'] == null || option['enddate'] == "") {
        option['enddate'] = '9998-12-31';
    }
    //logger.debug('enddate:' + option['enddate']);
    //logger.debug('startdate:' + option['startdate']);
    if (option['startdate'] != null && option['startdate'] != "") {
        option['dateCreated'] = {"$gte": new Date(option['startdate'])};
    }

    if (option['enddate'] != null && option['enddate'] != "") {
        if (option['dateCreated'] != null && option['dateCreated'] != "") {
            option['dateCreated'] = {
                "$gte": moment(option['startdate'])._d,
                "$lte": moment(option['enddate']).add(1, 'day')._d
            };
        } else {
            option['dateCreated'] = {"$lte": moment(option['enddate']).add(1, 'day')._d};
        }
    }
    option['startdate'] = null;
    option['enddate'] = null;
    logger.debug(option);
    for (var item in option) {
        if (option[item] == null) {
            delete option[item];
        }
    }

    var sortType = option.sortType == "reply" ? {
        categoryOrder:-1,
        dateLastModified: -1
    } : {
        categoryOrder:-1,
        dateCreated: -1
    };

    var sortTypeAll = option.sortType == "reply" ? {
        dateLastModified: -1
    } : {
        dateCreated: -1
    };

    delete option['sortType'];

    logger.debug(option);

    Community.find({}).exec(function (err, result) {
        var arry = {};
        async.each(result, function (item, callback) {
            arry[item.id] = item;
            callback();
        }), function (err) {

        };

        //logger.debug(arry);

        async.series([
            function (callback) {
                //logger.debug(option['nick']);
                if (option['createdBy'] == null) {

                    var useropt = {};
                    if (option['nick'] != undefined && option['nick'] != null && option['nick'] != "") {
                        useropt['nickName'] = new RegExp(option['nick']);
                    }
                    else {
                        useropt['_id'] = null;
                    }
                    Users.find(useropt, function (err, results) {
                        if (results.length > 0) {
                            var queryUserIn = {};
                            queryUserIn["$in"] = [];
                            for (var i = 0, l = results.length; i < l; i++) {
                                queryUserIn["$in"].push(results[i]['_id']);
                            }
                            ;
                            option["createdBy"] = queryUserIn;
                        }
                        callback(null, null);
                    });
                } else {
                    callback(null, null);
                }
            },
            function (callback) {
                option['nick'] = null;
                //logger.debug('sdfs');
                //logger.debug(option);
                Question.count(option, function (err, count) {
                    //logger.debug(option);
                    //logger.debug(count);
                    callback(err, Math.ceil(count / size));
                });
                //callback(null,null);
            },
            function (callback) {
                if (option.category != null) {
                    logger.debug(option);

                    Question.find(option, '_id categoryOrder desc community aroundCommunity replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount praiseCount category status tag images replies dateCreated dateLastModified createdBy recommend level')
                        .skip(index).limit(size).populate('tag', 'value').populate('replies.repliedBy', '_id community nickName images authenticationStatus')
                        .populate('community', '_id communityName').populate('aroundCommunity', '_id communityName').populate('createdBy', '_id nickName userType images authenticationStatus')
                        .sort(sortType).exec(function (err, results) {
                            //logger.debug('results');
                            //logger.debug(results.length);
                            if (err) {
                                return callback(err);
                            } else {
                                if (results != null) {
                                    results.forEach(function (question) {
                                        var data = [];
                                        if (question.tag != null) {
                                            question.tag.forEach(function (t) {
                                                data.push(t.value);
                                            });
                                            question._doc.tag = data;
                                        }

                                        logger.debug(question.aroundCommunity);
                                        // 周边小区
                                        data = [];
                                        if (question.aroundCommunity != null) {
                                            question.aroundCommunity.forEach(function (t) {
                                                data.push(t.communityName);
                                            });
                                            question._doc.aroundCommunity = data;
                                        }


                                        if (question.images != null) {
                                            question.images.forEach(function (img) {
                                                img.imageURL = fastDfsHostIp + img.imageURL;
                                                logger.debug(img.imageURL);
                                            });
                                        }
                                        if (question.dateLastModified > date) {
                                            question.dateLastModified = question.dateCreated;
                                        }
                                        if (question.replies != null) {
                                            //logger.debug(question.replies);
                                            question.replies.forEach(function (repliy) {
                                                var communityName = '';
                                                if (repliy.repliedBy.nickName != '小6客服') {
                                                    communityName = arry[repliy.repliedBy.community]['communityName'];
                                                }
                                                repliy.repliedBy._doc['communityName'] = communityName;

                                            });
                                        }

                                    });

                                }
                                return callback(null, results);
                            }
                        })
                } else {
                    logger.debug(option.category);
                    //logger.debug(option);

                    Question.find(option, '_id allOrder desc community aroundCommunity replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount praiseCount category status tag images replies dateCreated dateLastModified createdBy recommend level')
                        .skip(index).limit(size).populate('tag', 'value').populate('replies.repliedBy', '_id community nickName images authenticationStatus')
                        .populate('community', '_id communityName').populate('aroundCommunity', '_id communityName').populate('createdBy', '_id nickName userType images authenticationStatus')
                        .sort(sortTypeAll).exec(function (err, results) {
                            if (err) {
                                return callback(err);
                            } else {
                                if (results != null) {
                                    async.each(results, function(question, callback){
                                        var data = [];
                                        if (question.tag != null) {
                                            question.tag.forEach(function (t) {
                                                data.push(t.value);
                                            });
                                            question._doc.tag = data
                                        }

                                        logger.debug(question.aroundCommunity);
                                        // 周边小区
                                        data = [];
                                        if (question.aroundCommunity != null) {
                                            question.aroundCommunity.forEach(function (t) {
                                                data.push(t.communityName);
                                            });
                                            question._doc.aroundCommunity = data;
                                        }

                                        if (question.images != null) {
                                            question.images.forEach(function (img) {
                                                img.imageURL = fastDfsHostIp + img.imageURL;
                                                //logger.debug(img.imageURL);
                                            });
                                        }
                                        if (question.dateLastModified > date) {
                                            question.dateLastModified = question.dateCreated;
                                        }

                                        if (question.replies != null) {
                                            async.each(question.replies, function(repliy, callback){
                                                var communityName = '';
                                                if (repliy.repliedBy.nickName != '小6客服') {
                                                    communityName = arry[repliy.repliedBy.community]['communityName'];
                                                }
                                                repliy.repliedBy._doc['communityName'] = communityName;

                                                replyAt.findOne({replyId: repliy._id + ''}, function (err, at) {
                                                    if (at != null && at.uList != null) {
                                                        at.uList.forEach(function (temp, i) {
                                                            if(temp.nickName != undefined)repliy.replyDesc = repliy.replyDesc.replace(new RegExp("@\\{" + i + "\\}"), '@' + temp.nickName + ' ')
                                                        });
                                                    }
                                                    callback(null);// must call once
                                                }).populate('uList', '_id nickName');

                                            }, function(err){
                                                callback(null);// must call once
                                            });
                                        }
                                    }, function(err){
                                        callback(null, results)
                                    });
                                }

                            }
                        })
                }
            }

        ], callback);
    });
};

exports.searchUserQuestionService = function (userId, callback) {
    Question.find({
        $or: [{
            'createdBy': userId,
            'isValid': true
        }, {
            'createdBy': {'$ne': userId},
            'replies.repliedBy': userId,
            'isValid': true
        }]
    }, function (err, results) {
        var data = [];
        if (results == null) {
            callback(err, data);
        } else {
            results.forEach(function (question) {
                question._doc['isCreated'] = true;
                if (question.replies != null) {
                    if (userId != question.createdBy) {
                        question.replies.forEach(function (reply) {
                            if (userId == reply.repliedBy) {
                                question._doc['myReply'] = reply.replyDesc;
                                question._doc['isCreated'] = false;
                            }
                        });
                    }
                }
            });

            results.sort(function (a, b) {
                if (!a._doc.isCreated && b._doc.isCreated) {
                    return 1;
                }
            });
            callback(err, results)
        }
    })
};

exports.recommendQuestionService = function (questionId, flag, callback) {
    async.series([
        function (callbackInner) {
            Question.update({_id: questionId}, {recommend: flag, displayOrder: 0}, callbackInner)
        },
        function (callbackInner) {

            Question.findOne({'_id': questionId}, function (err, result) {
                var replyC = 0;
                if (result.replies != null) {
                    replyC = result.replies.length;
                }

                Dic.findOne({'value': '推荐', 'category': '02'}, '_id', function (err, res) {
                    QuestionAndReplyCount.findOne({
                        'community': result.community,
                        'tag': res._id
                    }, '', function (err, qc) {
                        if (qc == null) {
                            var temp = new QuestionAndReplyCount();
                            temp.questionCount = 1;
                            temp.replyCount = replyC;
                            temp.community = result.community;
                            temp.tag = res;
                            temp.save();
                        } else {
                            if (flag == 'true') {
                                qc.questionCount += 1;
                                qc.replyCount += replyC;
                            } else {
                                qc.questionCount -= 1;
                                qc.replyCount -= replyC;
                            }
                            qc.save();
                        }
                        callbackInner(err, null);
                    });
                })
            });
        }
    ], callback)
};

exports.getFreshNewsQuestionService = function (callback) {
    freshNews.find({}, 'newsId', callback);
};

exports.addQuestionToFreshNewsService = function (input, callback) {
    async.series([
        //function (callbackInner) {
        //    freshNews.remove({tag: '话题', community: input.community._id}, callbackInner);
        //},
        function (callbackInner) {
            var temp = new freshNews();
            temp.openType = 3;
            temp.tag = freshName.question.tagName;
            temp.newsId = input._id;
            temp.createdBy = input.createdBy._id;
            temp.title = input.desc;
            temp.bgColor = freshName.question.bgColor;
            temp.community = input.community._id;
            temp.save(callbackInner);
        }
    ], callback)
};

exports.pushQuestionByTagService = function (question, callback) {
    Dic.find({value: {$in: question.tag}, category: '01'}, '_id value', function (err, tags) {
        var uList = [];
        async.each(tags, function (tag, callbackInner) {
            Users.find({hobbies: tag._id, community: question.community}, '_id', function (err, users) {
                if (users != null) {
                    users.forEach(function (user) {
                        if (!contains(uList, user._id)) {
                            uList.push(user._id + '');
                        }
                    })
                }
                callbackInner(null, null);
            })
        }, function (err) {
            pushRecords.find({
                messageId: question._id,
                messageType: 'question'
            }, 'toUser', function (err, users) {
                var recordUsers = [];
                if (users != null) {
                    users.forEach(function (user) {
                        recordUsers.push(user.toUser + '');
                    })
                }

                var data = [];
                console.log(recordUsers);
                console.log(uList);
                uList.forEach(function (userId) {
                    if (!contains(recordUsers, userId)) {
                        data.push(userId)
                    }
                });
                callback(null, data)

            })
        })
    })
};


function contains(array, obj) {
    var i = array.length;
    while (i--) {
        if (array[i] === obj) {
            return true;
        }
    }
    return false;
}

exports.changeQuestionCategoryService = function (questionId, category, callback) {
    var replyC = 0;
    var communityId;
    async.series([
        function (callbackInner) {
            Question.findOne({_id: questionId}, function (err, result) {
                communityId = result.community;
                if (result.replies != null) {
                    replyC = result.replies.length;
                }
                if (result.category != null) {
                    redisClient.hincrby('q:count:' + result.community, result.category + 'QuestionCount', -1);
                    redisClient.hincrby('q:count:' + result.community, result.category + 'ReplyCount', -replyC);
                }
                if (category != result.category) {
                    result.categoryOrder = undefined;
                }
                result.save(callbackInner);
            });
        },
        function (callbackInner) {
            /*  宝宝树66小区二次改造    mod   luolh  20170720   start   */
            // Question.update({_id: questionId}, {category: category, }, callbackInner)
            Question.update({_id: questionId}, {$set:{category: category, dateCreated: new Date().getTime()}}, callbackInner)
            /*  宝宝树66小区二次改造    mod   luolh  20170720   end   */
        },
        function (callbackInner) {
            redisClient.hincrby('q:count:' + communityId, category + 'QuestionCount', 1);
            redisClient.hincrby('q:count:' + communityId, category + 'ReplyCount', replyC);
            callbackInner(null, null);
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: questionId}, {category: category}, callbackInner);
        }
    ], callback)
};

exports.changeQuestionLevelService = function (input, callback) {
    async.series([
        function (callbackInner) {
            /*  宝宝树宝宝树66小区二次改造    mod   luolh  20170720   start   */
            // Question.update({_id: input.questionId}, {level: input.level}, callbackInner);
            var dateCreatedTime = new Date().getTime();
            var updateData = {$set:{
                level: input.level,
                dateCreated: dateCreatedTime}
            };
            Question.update({_id: input.questionId}, updateData, callbackInner)
            /*  宝宝树宝宝树66小区二次改造    mod   luolh  20170720   end   */
        },
        function (callbackInner) {
            var body = {
                user_id : input.userId
                ,action : 'level'
                ,action_id : input.questionId
            };
            logger.debug(body);
            var sql = "insert into 66xiaoqu_log.user_action_log set ?";
            mysqlUtil.queryBI(sql, [body], function (err, result) {
                callbackInner(err, result);
            });
        },
        function (callbackInner) {
            ugcIndex.update({ugcId: input.questionId}, {level: input.level}, callbackInner);
        },
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  start   */
        function (callbackInner) {
            var userId =  input.setUserId; // 小区大使ID
            var questionId = input.questionId; // 问题ID
            // essence:精华
            var addFlag = -1; // 取消精华
            var operationType = '取消精华'; // 取消精华
            if(input.level == '1') { // 设置精华
                addFlag = 1;
                operationType = '精华'; // 精华
            }
            userService.incModeratorManager(userId, 'essence', addFlag, callbackInner);
            userService.saveModeratorManagerOperationNote(userId, questionId, operationType, null);
        },

        // var userId =  input.userId;
        // var questionId = input.questionId;

        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  end   */
        function (callbackInner) {
            ugcIndex.update({ugcId: input.questionId}, {level: input.level}, callbackInner);
        },
        function(callbackInner){

            /*  宝宝树宝宝树66小区二次改造    del   luolh  20170719   start   */
            callbackInner(null);
            // if(input.level == 1) {
            // var arg = {
            //     userId: input.userId + '',
            //     userRole: Number(input.userRole),
            //     userActionType: 13
            // };
            //
            // arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
            // logger.debug(arg);
            // scoreProxy.invoke('addScore', [arg], function (err, reply) {
            //     try {
            //         logger.debug(reply);
            //         var data = JSON.parse(decodeURIComponent(reply));
            //         if (err) {
            //             logger.error('hessianInvokeAddScore-----2' + err.message);
            //             callbackInner(null);
            //         } else if (data.status != 0) {
            //             logger.error('hessianInvokeAddScore----3' + data.status + '----' + data.msg);
            //             callbackInner(null);
            //         } else {
            //             callbackInner(null);
            //         }
            //     } catch (e) {
            //         logger.error('hessianInvokeAddScore---4' + e);
            //         callbackInner(e);
            //     }
            // });
            // }else{
            //     callbackInner(null);
            // }
            /*  宝宝树宝宝树66小区二次改造    del   luolh  20170719   end   */
        }
    ], callback);
};


exports.getQuestionByFilter = function (option, callback) {

    if (option['desc'] != null) {
        option['desc'] = new RegExp(option['desc']);
    }

    logger.debug(option);
    Question.find(option, '_id categoryOrder desc community aroundCommunity replies.replyStatus replies._id replies.replyDesc replies.images.imageURL replies.images._id replies.dateReplied replies.repliedBy browserCount category status tag images replies dateCreated dateLastModified createdBy recommend level')
        .populate('tag', 'value')
        .populate('replies.repliedBy', '_id community nickName images authenticationStatus')
        .populate('community', '_id communityName')
        .populate('aroundCommunity', '_id communityName')
        .populate('createdBy', '_id nickName images authenticationStatus').sort({
            community: 1,
            categoryOrder: -1,
            dateLastModified: -1
        })
        .exec(function (err, results) {
            if (err) {
                return callback(err);
            } else {
                return callback(null, results);
            }
        });

};
